JavaScript DOM Forms

Working with forms, inputs, and form validation using JavaScript

📝 What are DOM Forms?

DOM Forms allow you to interact with HTML forms using JavaScript. You can get form data, validate inputs, and respond to form events like submitting or typing.


// Get form data
let name = document.getElementById("nameInput").value;

// Validate and respond
if (name === "") {
    alert("Please enter your name!");
}
                                    

Form Interaction Methods

📥

Getting Values

Get data from form inputs

input.value
📤

Setting Values

Set data in form inputs

input.value = "New text"

Validation

Check if form data is correct

if (input.value === "")
🎯

Events

Respond to form interactions

form.onsubmit = function()

🔹 Getting Form Values

The most common task is getting what users type into forms:

<form>
    <label>Your Name:</label>
    <input type="text" id="userName" placeholder="Enter your name">
    
    <label>Your Age:</label>
    <input type="number" id="userAge" placeholder="Enter your age">
    
    <button type="button" onclick="getFormData()">Get Data</button>
</form>

<div id="output"></div>

<script>
function getFormData() {
    // Get values from inputs
    let name = document.getElementById("userName").value;
    let age = document.getElementById("userAge").value;
    
    // Display the data
    let output = document.getElementById("output");
    output.innerHTML = "<h4>Form Data:</h4>" +
                      "<p>Name: " + name + "</p>" +
                      "<p>Age: " + age + "</p>";
}
</script>

Try it:

🔹 Form Validation

Always check if users entered valid data:

<form>
    <label>Email:</label>
    <input type="email" id="userEmail" placeholder="Enter your email">
    
    <label>Password:</label>
    <input type="password" id="userPassword" placeholder="Enter password">
    
    <button type="button" onclick="validateForm()">Submit</button>
</form>

<div id="message"></div>

<script>
function validateForm() {
    let email = document.getElementById("userEmail").value;
    let password = document.getElementById("userPassword").value;
    let message = document.getElementById("message");
    
    // Check if fields are empty
    if (email === "" || password === "") {
        message.innerHTML = "<p style='color: red;'>Please fill in all fields!</p>";
        return;
    }
    
    // Check email format (simple check)
    if (!email.includes("@")) {
        message.innerHTML = "<p style='color: red;'>Please enter a valid email!</p>";
        return;
    }
    
    // Check password length
    if (password.length < 6) {
        message.innerHTML = "<p style='color: red;'>Password must be at least 6 characters!</p>";
        return;
    }
    
    // If everything is valid
    message.innerHTML = "<p style='color: green;'>Form is valid! ✅</p>";
}
</script>

Try it:

🔹 Working with Different Input Types

Different input types need different approaches:

<form>
    <!-- Text input -->
    <input type="text" id="textInput" value="Default text">
    
    <!-- Checkbox -->
    <input type="checkbox" id="checkboxInput"> I agree
    
    <!-- Radio buttons -->
    <input type="radio" name="color" value="red" id="redRadio"> Red
    <input type="radio" name="color" value="blue" id="blueRadio"> Blue
    
    <!-- Select dropdown -->
    <select id="selectInput">
        <option value="option1">Option 1</option>
        <option value="option2">Option 2</option>
    </select>
    
    <button type="button" onclick="getAllValues()">Get All Values</button>
</form>

<script>
function getAllValues() {
    // Text input
    let textValue = document.getElementById("textInput").value;
    
    // Checkbox (returns true/false)
    let checkboxValue = document.getElementById("checkboxInput").checked;
    
    // Radio buttons
    let redRadio = document.getElementById("redRadio").checked;
    let blueRadio = document.getElementById("blueRadio").checked;
    let selectedColor = redRadio ? "red" : (blueRadio ? "blue" : "none");
    
    // Select dropdown
    let selectValue = document.getElementById("selectInput").value;
    
    console.log("Text:", textValue);
    console.log("Checkbox:", checkboxValue);
    console.log("Selected color:", selectedColor);
    console.log("Select:", selectValue);
}
</script>

🔹 Form Events

Respond to user actions on forms:

// When user types in input
document.getElementById("myInput").oninput = function() {
    console.log("User is typing: " + this.value);
};

// When input loses focus
document.getElementById("myInput").onblur = function() {
    console.log("User finished typing: " + this.value);
};

// When form is submitted
document.getElementById("myForm").onsubmit = function(event) {
    event.preventDefault(); // Stop form from submitting normally
    console.log("Form submitted!");
};

🔸 Live Character Counter Example:

<textarea id="messageInput" placeholder="Type your message..." maxlength="100"></textarea>
<p id="charCounter">0 / 100 characters</p>

<script>
document.getElementById("messageInput").oninput = function() {
    let currentLength = this.value.length;
    let maxLength = 100;
    let counter = document.getElementById("charCounter");
    
    counter.innerHTML = currentLength + " / " + maxLength + " characters";
    
    // Change color when getting close to limit
    if (currentLength > 80) {
        counter.style.color = "red";
    } else if (currentLength > 60) {
        counter.style.color = "orange";
    } else {
        counter.style.color = "green";
    }
};
</script>

Try it:

0 / 100 characters

🔹 Complete Form Example

Here's a complete contact form with validation:

<form id="contactForm">
    <h3>Contact Us</h3>
    
    <label>Name: *</label>
    <input type="text" id="contactName" required>
    
    <label>Email: *</label>
    <input type="email" id="contactEmail" required>
    
    <label>Message: *</label>
    <textarea id="contactMessage" required></textarea>
    
    <button type="submit">Send Message</button>
</form>

<div id="formResult"></div>

<script>
document.getElementById("contactForm").onsubmit = function(event) {
    event.preventDefault(); // Don't submit normally
    
    // Get all values
    let name = document.getElementById("contactName").value.trim();
    let email = document.getElementById("contactEmail").value.trim();
    let message = document.getElementById("contactMessage").value.trim();
    let result = document.getElementById("formResult");
    
    // Validate
    if (name === "" || email === "" || message === "") {
        result.innerHTML = "<p style='color: red;'>All fields are required!</p>";
        return;
    }
    
    if (!email.includes("@") || !email.includes(".")) {
        result.innerHTML = "<p style='color: red;'>Please enter a valid email!</p>";
        return;
    }
    
    // Success
    result.innerHTML = "<p style='color: green;'>Thank you " + name + "! Your message has been sent.</p>";
    
    // Clear form
    this.reset();
};
</script>

🧠 Test Your Knowledge

How do you get the value from an input field with id="myInput"?