Skip to content

JavaScript Forms in the DOM

Forms are fundamental components of web applications, enabling user interaction and data collection. This guide will help you understand how to access form elements, get and set input values, handle form events, and validate forms.

Accessing Form Elements

Selecting Form Elements

Form elements can be selected using various methods such as getElementById, getElementsByName, getElementsByTagName, and querySelector.


html
<!DOCTYPE html>
<html>
<head>
    <title>Selecting Form Elements</title>
</head>
<body>
<h4>Fill the form inputs, and press 'Show Input Values' button.</h4>
    <form id="userForm">
        <input type="text" id="username" name="username" placeholder="Username" />
        <input type="email" id="email" name="email" placeholder="Email" />
    </form>
    <button id="showInputs">Show Input Values</button>

    <script>
        // Select elements by ID
        const username = document.getElementById('username');
        const email = document.getElementById('email');
        const showInputsButton = document.getElementById('showInputs');

        // Using querySelector for selection
        const emailByQuery = document.querySelector('#email');

        showInputsButton.addEventListener('click', () => {
            alert(`Username: ${username.value}, Email: ${emailByQuery.value}`);
        });
    </script>
</body>
</html>

This example demonstrates selecting form elements using various methods and displaying their values in an alert when the "Show Input Values" button is clicked.

Getting and Setting Input Values

Accessing and Modifying Input Values

Input values can be accessed and modified using the value property.


html
<!DOCTYPE html>
<html>
<head>
    <title>Getting and Setting Input Values</title>
</head>
<body>
    <form id="userForm">
        <input type="text" id="username" name="username" placeholder="Username" />
        <input type="email" id="email" name="email" placeholder="Email" />
        <button type="button" id="showValues">Show Values</button>
        <button type="button" id="setValues">Set New Values</button>
    </form>

    <script>
        const username = document.getElementById('username');
        const email = document.getElementById('email');
        const showValuesButton = document.getElementById('showValues');
        const setValuesButton = document.getElementById('setValues');

        showValuesButton.addEventListener('click', () => {
            alert(`Username: ${username.value}\nEmail: ${email.value}`);
        });

        setValuesButton.addEventListener('click', () => {
            username.value = 'newUsername';
            email.value = '[email protected]';
            alert('Values have been set to new values.');
        });
    </script>
</body>
</html>

This example shows how to get and set the values of input fields. Clicking "Show Values" displays the current input values, and "Set New Values" changes them and displays a confirmation alert.

Form Events

Handling Form Submission with Submit and Reset Events

Forms can trigger events like submit and reset which can be handled to perform actions such as validation or data processing.


html
<!DOCTYPE html>
<html>
<head>
    <title>Form Events</title>
</head>
<body>
    <form id="userForm">
        <input type="text" id="username" name="username" placeholder="Username" />
        <input type="email" id="email" name="email" placeholder="Email" />
        <button type="submit">Submit</button>
        <button type="reset">Reset</button>
    </form>

    <script>
        const form = document.getElementById('userForm');

        form.addEventListener('submit', (event) => {
            event.preventDefault();
            alert('Form submitted!');

            // Perform form validation or data processing here
        });

        form.addEventListener('reset', () => {
            alert('Form reset!');
        });
    </script>
</body>
</html>

This example shows how to handle the submit and reset events of a form to perform actions such as preventing default behavior, validation, and data processing.

Handling Real-Time User Interactions

In addition to submit and reset, forms frequently use input, change, focus, and blur events to react to user interactions in real time. The input event fires immediately as the user types, while change fires when the element loses focus after its value has changed.


html
<script>
    const inputField = document.getElementById('username');

    inputField.addEventListener('input', (e) => {
        console.log('User is typing:', e.target.value);
    });

    inputField.addEventListener('change', (e) => {
        console.log('Value changed:', e.target.value);
    });
</script>

Validation and Preventing Default Behavior

Validating Form Data

Client-side validation can be performed to ensure data correctness before form submission.


html
<!DOCTYPE html>
<html>
<head>
    <title>Form Validation</title>
</head>
<body>
    <form id="userForm">
        <input type="text" id="username" name="username" placeholder="Username" required />
        <input type="email" id="email" name="email" placeholder="Email" required />
        <button type="submit">Submit</button>
    </form>

    <script>
        const form = document.getElementById('userForm');

        form.addEventListener('submit', (event) => {
            event.preventDefault();

            const username = document.getElementById('username').value;
            const email = document.getElementById('email').value;

            if (!username || !email) {
                alert('Please fill in all fields.');
                return;
            }

            // Modern approach: use checkValidity() for built-in validation
            if (!form.checkValidity()) {
                form.reportValidity();
                return;
            }

            // Fallback/custom regex validation if needed
            const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            if (!emailRegex.test(email)) {
                alert('Please enter a valid email address.');
                return;
            }

            alert('Form submitted successfully!');
        });
    </script>
</body>
</html>

This example demonstrates client-side form validation, including required fields and email format validation, and preventing form submission if validation fails.

INFO

Use querySelector and querySelectorAll for efficient form element selection, and always validate input values before form submission to ensure data integrity and a seamless user experience.

WARNING

Client-side validation improves user experience but is not a substitute for server-side validation. Always validate and sanitize data on your backend as well.

Conclusion

Working with forms in JavaScript involves accessing form elements, getting and setting input values, handling form events, and validating form data. By mastering these techniques, you can create dynamic and responsive web forms that enhance user interaction and data collection.

Practice

Which of the following statements about handling forms in JavaScript are true?

Do you find this helpful?

Dual-run preview — compare with live Symfony routes.