Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent buttons from submitting forms

In the following page, with Firefox the remove button submits the form, but the add button does not.

How do I prevent the remove button from submitting the form?

function addItem() {   var v = $('form :hidden:last').attr('name');   var n = /(.*)input/.exec(v);    var newPrefix;   if (n[1].length == 0) {     newPrefix = '1';   } else {     newPrefix = parseInt(n[1]) + 1;   }    var oldElem = $('form tr:last');   var newElem = oldElem.clone(true);   var lastHidden = $('form :hidden:last');    lastHidden.val(newPrefix);    var pat = '=\"' + n[1] + 'input';    newElem.html(newElem.html().replace(new RegExp(pat, 'g'), '=\"' + newPrefix + 'input'));   newElem.appendTo('table');   $('form :hidden:last').val(''); }  function removeItem() {   var rows = $('form tr');   if (rows.length > 2) {     rows[rows.length - 1].html('');     $('form :hidden:last').val('');   } else {     alert('Cannot remove any more rows');   } }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> <html> <body>     <form autocomplete="off" method="post" action="">         <p>Title:<input type="text" /></p>         <button onclick="addItem(); return false;">Add Item</button>         <button onclick="removeItem(); return false;">Remove Last Item</button>         <table>             <th>Name</th>              <tr>                 <td><input type="text" id="input1" name="input1" /></td>                 <td><input type="hidden" id="input2" name="input2" /></td>             </tr>         </table>         <input id="submit" type="submit" name="submit" value="Submit">     </form> </body>  </html>
like image 735
Khanpo Avatar asked May 31 '09 19:05

Khanpo


People also ask

How do you stop re submitting a form after clicking back button?

You can check if the user clicked the back button, disable form if true. Another way is by storing a cookie which you check on page load, if it exists you can disable the form.

How does JavaScript prevent a form from being submitted?

Use the return value of the function to stop the execution of a form in JavaScript. False would return if the form fails to submit.


1 Answers

You're using an HTML5 button element. Remember the reason is this button has a default behavior of submit, as stated in the W3 specification as seen here: W3C HTML5 Button

So you need to specify its type explicitly:

<button type="button">Button</button> 

in order to override the default submit type. I just want to point out the reason why this happens.

like image 127
Metafaniel Avatar answered Sep 22 '22 12:09

Metafaniel