A submit
button's job is to trigger the submit
event of a form
. Therefore, with form
elements, you don't set up click
events on the submit
button, you set up submit
event handlers on the form
.
Then, to introduce validation into the mix, you can stop the native submit
to take place in the handler, only if validation fails. This is done by accessing the event
argument that is automatically sent to every DOM event handler* (see next paragraph for caveat). You can use the event.preventDefault()
method to stop the native event from taking place.
*One final note, the use of inline HTML event handling attributes such as onsubmit
and onclick
is to be avoided. This is a 25+ year old technique that we used before we had standards and unfortunately, because they seem easy to use, they get copied by new developers who don't know any better. There are real reasons not to use them and you've stumbled into one. Your e
argument to your event handling function is not being populated with a reference to the event
like you think it is. That only happens when you use the modern standard way of setting up event callbacks, which is .addEventListener()
.
// Set up a submit event handler for the form
// not a click event handler for the button because
// clicking a submit button triggers the form's submit event
document.querySelector("form").addEventListener("submit", function(event){
if(document.querySelector("input").value === ""){
// Invalid data! Stop the submit!
event.preventDefault();
alert("Please fill in all fields!");
return;
}
// If the code reaches this point, validation succeeded
console.log("Form submitted");
});
<form action="https://example.com" method="post">
<input>
<button>Submit</button>
</form>