I have a form. Outside that form, I have a button. A simple button, like this:
<button>My Button</button>
Nevertheless, when I click it, it submits the form. Here's the code:
<form id="myform"> <input /> </form> <button>My Button</button>
All this button should do is some JavaScript. But even when it looks just like in the code above, it submits the form. When I change the tag button to span, it works perfectly. But unfortunately, it needs to be a button. Is there any way to block that button from submitting the form? Like e. g.
<button onclick="document.getElementById('myform').doNotSubmit();">My Button</button>
The simplest solution to prevent the form submission is to return false on submit event handler defined using the onsubmit property in the HTML <form> element.
The default value for the type attribute of button elements is "submit". Set it to type="button" to produce a button that doesn't submit the form. In the words of the HTML Standard: "Does nothing."
Both <button type="submit"> and <input type="submit"> display as buttons and cause the form data to be submitted to the server. The difference is that <button> can have content, whereas <input> cannot (it is a null element).
I think this is the most annoying little peculiarity of HTML... That button needs to be of type "button" in order to not submit.
<button type="button">My Button</button>
Update 5-Feb-2019: As per the HTML Living Standard (and also HTML 5 specification):
The missing value default and invalid value default are the Submit Button state.
return false;
at the end of the onclick handler will do the job. However, it's be better to simply add type="button"
to the <button>
- that way it behaves properly even without any JavaScript.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With