Episode 45 of 46

Accessing Form Elements

Learn how to access and read values from HTML form elements with JavaScript.

Forms are essential for collecting user input. JavaScript lets you access and manipulate every form element.

Accessing the Form

// By ID
let form = document.getElementById("myForm");

// By name attribute
let form = document.forms["myForm"];

// First form on page
let form = document.forms[0];

Accessing Input Values

<form id="signup">
    <input type="text" id="username" name="username">
    <input type="email" id="email" name="email">
    <input type="password" id="password" name="password">
    <button type="submit">Sign Up</button>
</form>
let form = document.getElementById("signup");

// Access by ID
let username = document.getElementById("username").value;

// Access via form's elements
let email = form.elements["email"].value;
let password = form.elements.password.value;

Different Input Types

// Text input
document.getElementById("name").value;       // "Alice"

// Checkbox
document.getElementById("agree").checked;    // true or false

// Radio buttons
let radios = document.getElementsByName("color");
for (let radio of radios) {
    if (radio.checked) {
        console.log("Selected:", radio.value);
    }
}

// Select dropdown
let select = document.getElementById("country");
console.log(select.value);              // Selected option value
console.log(select.selectedIndex);       // Index of selected option

// Textarea
document.getElementById("message").value;  // Text content

Handling Form Submission

let form = document.getElementById("signup");

form.addEventListener("submit", function(e) {
    e.preventDefault();  // Stop default form submission

    let data = {
        username: form.elements.username.value,
        email: form.elements.email.value,
        password: form.elements.password.value
    };

    console.log("Form data:", data);
});