Step 6
Let's explore the script.js
file. Notice the following statements where we add an event listener to the submit button:
const submitBtn = document.getElementById("submit");
submitBtn.addEventListener("click", handleFormSubmit);
The second statement tells the browser to call the handleFormSubmit
function when the submit button is clicked.
Let's explore the handleFormSubmit
function:
function handleFormSubmit(event) {
event.preventDefault();
// The remaining code not shown to space space here!
}
The preventDefault()
method, when called in response to clicking on a "Submit" button, prevents it from submitting a form.
Let's make an experiment. Comment out the entire body of handleFormSubmit
function except for event.preventDefault();
. Then open the index.html
in a browser and press the submit button.
Notice how the submit button isn't doing anything!! Unfortunately, all the validation behaviour is also prevented by using event.preventDefault();
.