JavaScript Q&A Logo
JavaScript Q&A Part of the Q&A Network

How do I work with forms using JavaScript?

Asked on Aug 15, 2024

Answer

To work with forms using JavaScript, you can manipulate form elements, validate input, and handle form submissions. Here's a basic example of handling a form submission and preventing the default behavior.
<!-- BEGIN COPY / PASTE -->
        <form id="myForm">
            <input type="text" id="name" placeholder="Enter your name" required>
            <button type="submit">Submit</button>
        </form>

        <script>
            document.getElementById('myForm').addEventListener('submit', function(event) {
                event.preventDefault(); // Prevents the default form submission
                const name = document.getElementById('name').value;
                console.log('Form submitted with name:', name);
            });
        </script>
        <!-- END COPY / PASTE -->
Additional Comment:
  • The "submit" event listener is added to the form to intercept the submission.
  • "event.preventDefault()" is used to stop the form from submitting in the traditional way, allowing you to handle it with JavaScript.
  • The value of the input field is accessed using "document.getElementById('name').value".
  • You can further process the form data or send it to a server using AJAX.
✅ Answered with JavaScript best practices.
← Back to All Questions