How to prevent butt...
Notifications
Clear all

How to prevent buttons from submitting forms

RSS

(@abhijith)
Noble Member
Joined: 12 months ago
Posts: 1350
19日/07/2021 12:41 pm

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

How do I prevent the removebutton from submitting the form?

functionaddItem() {varv = $('form :hidden:last').attr('name');varn =/(.*)input/.exec(v);varnewPrefix;if(n[1].length==0) { newPrefix ='1'; }else{ newPrefix =parseInt(n[1]) +1; }varoldElem = $('form tr:last');varnewElem = oldElem.clone(true);varlastHidden = $('form :hidden:last'); lastHidden.val(newPrefix);varpat ='=\"'+ n[1] +'input'; newElem.html(newElem.html().replace(newRegExp(pat,'g'),'=\"'+ newPrefix +'input')); newElem.appendTo('table'); $('form :hidden:last').val(''); }functionremoveItem() {varrows = $('form tr');if(rows.length>2) { rows[rows.length-1].html(''); $('form :hidden:last').val(''); }else{alert('Cannot remove any more rows'); } }
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.3.2/jquery.min.js">script><html><body><formautocomplete="off"method="post"action=""><p>Title:<inputtype="text"/>p><buttononclick="addItem(); return false;">Add Itembutton><buttononclick="removeItem(); return false;">Remove Last Itembutton><table><th>Nameth><tr><td><inputtype="text"id="input1"name="input1"/>td><td><inputtype="hidden"id="input2"name="input2"/>td>tr>table><inputid="submit"type="submit"name="submit"value="Submit">form>body>html>

Quote
(@abhijith)
Noble Member
Joined: 12 months ago
Posts: 1350
19日/07/2021 12:43 pm

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:

<buttontype="button">Buttonbutton>

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


ReplyQuote
Share:
Baidu