Why does my Cancel button submit the form?
Here's something that's easy to miss when working with HTML forms. Say you have a form with two buttons: <form> <input type="text" name="username"> <button>Cancel</button> <button>Save</button> </form> L
Here's something that's easy to miss when working with HTML forms.
Say you have a form with two buttons:
<form>
<input type="text" name="username">
<button>Cancel</button>
<button>Save</button>
</form>
Looks fine, right?
But clicking "Cancel" will also try to submit the form.
That's because a <button> inside a form defaults to type="submit" when you don't specify a type.
It doesn't matter what text is inside the button. The browser doesn't know that "Cancel" is supposed to cancel something.
The fix is just to be explicit:
<form>
<input type="text" name="username">
<button type="button">Cancel</button>
<button type="submit">Save</button>
</form>
Now the Cancel button won't submit the form. You can attach your own JavaScript to it, like closing a modal or going back to another page.
There's also type="reset", but that's different. It restores form fields to their initial values, which isn't necessarily what you want from a Cancel button.
One other thing: this behavior isn't limited to buttons physically inside a <form>. A button outside the form can still be associated with it using the form attribute.
So if a form is submitting when you click something that shouldn't submit it, checking the button's type is a good place to start.
I usually prefer writing type="button" or type="submit" explicitly, even when the default would work. It's one less thing to think about later.
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes β full credit and traffic to the original publisher.