Learn Dynamic HTML With JS
Lesson 1 - HTML JS Relationship
Lesson 2 - HTML DOM
Lesson 3 - Browser BOM
Lesson 4 - Basic Interaction
Lesson 5 - Manipulating CSS
Lesson 6 - HTTP Requests
In the previous section, we created the HTML form and learned how to retrieve the input values.
Now, we need to implement a form submission handler. When a user clicks the submit button within the <form>
, the form is automatically submitted. We want to intercept this process, prevent the default submission behavior, capture the input values, and display them somewhere.
submit
Event Listener// Access the form element const formElement = document.getElementById('userForm'); // Add Submit Handler formElement.addEventListener('submit', function(event) { event.preventDefault(); // Callback Handler });
The callback handler function is executed when the form is submitted.
document.getElementById('userForm').addEventListener('submit', function(event) { event.preventDefault(); const username = document.getElementById('username').value; const email = document.getElementById('email').value; document.getElementById('responseMessage').innerText = `Submitted! Username: ${username}, Email: ${email}`; });
This code prevents the default form submission behavior, retrieves the input values for username and email, and then displays a message with the submitted values.
<!DOCTYPE html> <html> <head> <title>Form Handling</title> </head> <body> <form id="userForm"> <label for="username">Username:</label> <input type="text" id="username" name="username" required> <label for="email">Email:</label> <input type="email" id="email" name="email" required> <button type="submit">Submit</button> </form> <p id="responseMessage"></p> <script> document.getElementById('userForm').addEventListener('submit', function(event) { event.preventDefault(); const username = document.getElementById('username').value; const email = document.getElementById('email').value; document.getElementById('responseMessage').innerText = `Submitted! Username: ${username}, Email: ${email}`; }); </script> </body> </html>