W3docs

JavaScript Form Properties and Methods

Learn JavaScript form properties and methods: document.forms, form.elements, reading input values, checkboxes and selects.

Introduction to JavaScript Form Handling

Forms are the primary way users send data to a web page, so reaching their controls reliably from JavaScript is a core skill. The DOM exposes forms and the fields inside them through a set of dedicated collections (document.forms, form.elements) and properties (input.value, checkbox.checked, select.value), plus a few imperative methods (submit(), reset(), focus()).

This chapter covers how to reach forms and controls, read and write their values, react to user input with the input and change events, and trigger common actions programmatically. For the broader picture of where forms sit in the document tree, see Working with forms in the DOM.

Reaching Forms and Their Controls

document.forms and form.elements

Every form on a page is available through document.forms. This is a special collection you can index by number (document.forms[0]) or, more readably, by the form's name attribute (document.forms.loginForm or document.forms['loginForm']).

Once you have a form, form.elements gives you its named controls in exactly the same way — by index or by the control's name. Named access is the recommended style because it keeps working even when you add or reorder fields:

const form = document.forms.loginForm;     // a <form name="loginForm">
const userField = form.elements.username;  // an <input name="username">
// Shortcut: named controls are also exposed directly on the form
const samePassword = form.password;        // <input name="password">

When several controls share one name (radio buttons), form.elements.name returns a RadioNodeList — a collection whose .value is the value of the currently checked button. A <fieldset> also has its own elements collection, so you can treat a grouped section like a mini-form.

Here's a complete example that accesses a form and its inputs:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>JavaScript Form Example</title>
</head>
<body>
    <form name="loginForm">
        <input type="text" name="username" placeholder="Username" />
        <input type="password" name="password" placeholder="Password" />
        <input type="submit" value="Login" />
    </form>
    <div style="margin-top:15px;" id="output"></div>

    <script>
        const form = document.forms['loginForm'];
        const username = form.elements['username'];
        const password = form.elements['password'];
        form.onsubmit = function(event) {
            const output = document.getElementById('output');
            output.textContent = 'Username: ' + username.value + ' Password: ' + password.value;
            event.preventDefault(); // Prevent form submission
        }
    </script>
</body>
</html>

This script intercepts the form submission, displays the username and password in a div on the page, and prevents the form from being submitted to a server.

Reading and Writing Control Values

Each control type exposes its current state through a slightly different property — knowing which one to read is half the job:

ControlRead / write withNotes
text, password, email, textarea.valueAlways a string
checkbox.checked (boolean).value is the attribute value, not whether it's ticked
radio (group)form.elements.groupName.valueValue of the checked button, or ""
<select>.valueValue of the selected <option>; .options[i] and .selectedIndex give finer access
input.value = 'hello';            // text-like fields
checkbox.checked = true;          // tick a checkbox
select.value = 'medium';          // selects the matching <option>
const chosen = select.options[select.selectedIndex].text; // visible label

A common beginner trap is reading checkbox.value to find out whether a box is ticked — that returns the static attribute string ("on" by default), not its checked state. Use .checked instead.

Working with Input Values

Manipulating input values is straightforward in JavaScript. Here’s how you can dynamically set input values and display them on your webpage:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>Input Value Example</title>
</head>
<body>
    <form name="userForm">
        <input type="text" name="firstName" placeholder="First Name" />
        <input type="text" name="lastName" placeholder="Last Name" />
        <input type="submit" value="Submit" />
    </form>
    <div id="welcomeMessage"></div>

    <script>
        const form = document.forms['userForm'];
        const firstName = form.elements['firstName'];
        const lastName = form.elements['lastName'];
        firstName.value = 'John';
        lastName.value = 'Doe';

        form.onsubmit = function(event) {
            const welcomeMessage = document.getElementById('welcomeMessage');
            welcomeMessage.textContent = 'Hello, ' + firstName.value + ' ' + lastName.value + '!';
            event.preventDefault(); // Prevents the form from submitting to a server
        }
    </script>
</body>
</html>

In this example, the first and last names are pre-set to 'John' and 'Doe', respectively. When the form is submitted, a greeting is displayed on the page, demonstrating both setting and retrieving input values. For more complex forms, consider the FormData API to easily serialize form data into key-value pairs without manually accessing each element.

Advanced Form Techniques

Form Validation

Real-time form validation is critical for user experience. Here’s an example of how to validate an email address before form submission. Note that HTML5 email validation is basic and often supplemented by custom regex or libraries for production, as it may incorrectly accept incomplete addresses like 'w3docs@gmail' (If you want to know how to fix this, you can read JavaScript Validation API):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>Form Validation Example</title>
</head>
<body>
    <form name="registrationForm">
        <input type="email" name="email" placeholder="Enter your email" required />
        <input type="submit" value="Register" />
    </form>
    <div id="message"></div>

    <script>
        const form = document.forms['registrationForm'];
        const email = form.elements['email'];

        form.onsubmit = function(event) {
            // Note: HTML5 email validation is basic and often supplemented by custom regex or libraries for production.
            // It may incorrectly accept incomplete addresses like 'w3docs@gmail'.
            if (!email.checkValidity()) {
                document.getElementById('message').textContent = "Please enter a valid email address.";
                event.preventDefault();
                return;
            }
            document.getElementById('message').textContent = "Registration successful!";
            event.preventDefault(); // Prevents actual form submission
        }
    </script>
</body>
</html>

In this script, the form validates the email input on submission. It displays a message indicating whether the registration was successful or if there's an error, all without sending any data to a server. This example also highlights a limitation of HTML5 email validation, which does not fully ensure correct domain formats.

Reacting to input and change Events

Two events cover most form interactions:

  • input fires on every keystroke or value change — ideal for live previews, character counters, and as-you-type validation.
  • change fires only once the user commits a change: when a text field loses focus after editing, or immediately when a checkbox, radio, or <select> is toggled. Use it when reacting to each keystroke would be wasteful.
search.addEventListener('input', () => console.log(search.value)); // every keystroke
country.addEventListener('change', () => console.log(country.value)); // on selection

The next example uses input to show a live character count while the user types:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <title>Input Event Example</title>
</head>
<body>
  <form name="bioForm">
    <textarea name="bio" maxlength="100" placeholder="Tell us about yourself"></textarea>
  </form>
  <div id="counter">0 / 100</div>

  <script>
    const bio = document.forms.bioForm.elements.bio;
    const counter = document.getElementById('counter');
    bio.addEventListener('input', function () {
      counter.textContent = bio.value.length + ' / 100';
    });
  </script>
</body>
</html>

For the deeper mechanics of submission — including the difference between the submit event and the form.submit() method — see Forms: event and method submit.

Form Methods: submit(), reset(), and focus()

Forms and controls also offer imperative methods:

  • form.submit() sends the form programmatically. Important gotcha: it does not fire the submit event, so any validation wired to that event is skipped. Prefer form.requestSubmit() when you need validation and the event to run.
  • form.reset() restores every control to its initial value.
  • element.focus() moves the keyboard cursor to a control — perfect for highlighting the first invalid field. Its counterpart is blur(). See Focusing: focus / blur for details.
const form = document.forms.signup;
if (!form.email.value) {
  form.email.focus();   // send the user straight to the empty field
} else {
  form.requestSubmit(); // submit AND run the submit event + validation
}
form.reset();           // clear the form back to defaults

Handling Form Events

Here's how you can handle form events dynamically:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Form Events Example</title>
  </head>
  <body>
    <div style="display: flex; justify-content: center; align-items: center">
      <form
        style="display: flex; flex-direction: column; gap: 5px"
        name="contactForm"
      >
        <input type="text" name="fullName" placeholder="Full Name" required />
        <textarea name="message" placeholder="Your Message"></textarea>
        <input type="submit" value="Send" />
      </form>
    </div>
    <div
      style="display: flex; justify-content: center; align-items: center"
      id="confirmation"
    ></div>

    <script>
      const form = document.forms["contactForm"];

      form.onsubmit = function (event) {
        const name = form.elements["fullName"].value;
        const message = form.elements["message"].value;
        document.getElementById("confirmation").textContent =
          "Thank you, " + name + ", we received your message!";
        event.preventDefault(); // Prevents form from submitting to a server
      };
    </script>
  </body>
</html>

This example provides instant feedback to the user by displaying a confirmation message when the form is submitted. It effectively showcases how JavaScript can manage form events to improve interaction without server communication.

Conclusion

Mastering JavaScript form properties and methods enhances the functionality and user interaction of web applications. Reach forms through document.forms, address their controls by name with form.elements, read state with the right property (value, checked, selectedIndex), respond to input and change events, and drive the form with submit(), reset(), and focus().

To go further, continue with these related chapters:

Practice

Practice
Which of the following statements are true regarding JavaScript forms and their methods?
Which of the following statements are true regarding JavaScript forms and their methods?
Was this page helpful?