To create and handle form submit events using JavaScript, follow these steps:
document.querySelector()
or document.getElementById()
method.const form = document.querySelector('form');
addEventListener()
method and specify the event type as 'submit'
.form.addEventListener('submit', handleSubmit);
handleSubmit(event)
that will be executed when the form is submitted. The callback function takes an event
object as an argument.function handleSubmit(event) {
// Prevent the default form submit action
event.preventDefault();
// Access form inputs and values
const name = document.getElementById('name').value;
const email = document.getElementById('email').value;
// Do something with the form data
console.log(`Name: ${name}`);
console.log(`Email: ${email}`);
// Reset the form
form.reset();
}
In the example above, the handleSubmit()
function prevents the default form submit action using event.preventDefault()
. Then, it accesses the form inputs by their id
using the getElementById()
method and retrieves their values using the value
property. Finally, it handles the form data as required (e.g., sends it to a server, performs validation, etc.), and resets the form using the reset()
method.
Note: Make sure to add the id
attribute to the form inputs you want to access, like <input id="name" type="text">
.