Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML button to NOT submit form

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> 
like image 249
arik Avatar asked May 13 '10 10:05

arik


People also ask

How do I make a form not submit in HTML?

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.

How a button does not submit a form?

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."

Can I use button instead of submit?

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).


2 Answers

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.

like image 79
Dave Markle Avatar answered Sep 24 '22 19:09

Dave Markle


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.

like image 35
ThiefMaster Avatar answered Sep 24 '22 19:09

ThiefMaster