How to prevent buttons from submitting forms

2018-12-31 01:27发布

In the following page, with Firefox the remove button submits the form, but the add button doesn't. How do I prevent the remove button from submitting the form?

<html>
<head>
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<script type="text/javascript">
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>
</head>
<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>

16条回答
君临天下
2楼-- · 2018-12-31 01:40

i had solved this problem in three ways it will help to you

if we use jquery validation plugin in

$("form").validate({
      submitHandler: function (form) {
                     console.log('test');
                          }
                      });

2nd method using prevent default

    $( "form" ).submit(function( event ) {

      event.preventDefault();
console.log('test');
    });

3rd using javscript(onsubmit event)

if we use onsubmit event within form tag it triggers url instead if we use onsubmit in button or input which has type=submit

<button type="submit" onsubmit="submitfunction()">submit</button>
    function submitfunction(event){
event.preventDefault();
console.log('test');
}

hope it will help

查看更多
美炸的是我
3楼-- · 2018-12-31 01:42

This is an html5 error like has been said, you can still have the button as a submit (if you want to cover both javascript and non javascript users) using it like:

     <button type="submit" onclick="return false"> Register </button>

This way you will cancel the submit but still do whatever you are doing in jquery or javascript function`s and do the submit for users who dont have javascript.

查看更多
还给你的自由
4楼-- · 2018-12-31 01:43

Set the type on your buttons:

<button type="button" onclick="addItem(); return false;">Add Item</button>
<button type="button" onclick="removeItem(); return false;">Remove Last Item</button>

...that'll keep them from triggering a submit action when an exception occurs in the event handler. Then, fix your removeItem() function so that it doesn't trigger an exception:

function removeItem() {
  var rows = $('form tr');
  if ( rows.length > 2 ) {
    // change: work on filtered jQuery object
    rows.filter(":last").html('');
    $('form :hidden:last').val('');
  } else {
    alert('Cannot remove any more rows');
  }
}

Note the change: your original code extracted a HTML element from the jQuery set, and then tried to call a jQuery method on it - this threw an exception, resulting in the default behavior for the button.

FWIW, there's another way you could go with this... Wire up your event handlers using jQuery, and use the preventDefault() method on jQuery's event object to cancel the default behavior up-front:

$(function() // execute once the DOM has loaded
{

  // wire up Add Item button click event
  $("#AddItem").click(function(event)
  {
    event.preventDefault(); // cancel default behavior

    //... rest of add logic
  });

  // wire up Remove Last Item button click event
  $("RemoveLastItem").click(function(event)
  {
    event.preventDefault(); // cancel default behavior

    //... rest of remove last logic
  });

});

...

<button type="button" id="AddItem" name="AddItem">Add Item</button>
<button type="button" id="RemoveLastItem" name="RemoveLastItem">Remove Last Item</button>

This technique keeps all of your logic in one place, making it easier to debug... it also allows you to implement a fall-back by changing the type on the buttons back to submit and handling the event server-side - this is known as unobtrusive JavaScript.

查看更多
高级女魔头
5楼-- · 2018-12-31 01:55

I agree with Shog9, though I might instead use:

<input type = "button" onClick="addItem(); return false;" value="Add Item" />

According to w3schools, the <button> tag has different behavior on different browsers.

查看更多
临风纵饮
6楼-- · 2018-12-31 01:56

The following sample code show you how to prevent button click from submitting form.

You may try my sample code:

 <form autocomplete="off" method="post" action="">
   <p>Title:
     <input type="text" />
   </p>
   <input type="button" onclick="addItem()" value="Add Item">
   <input type="button" onclick="removeItem()" value="Remove Last Item">
   <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>
<script language="javascript">
function addItem() {
return false;
}

function removeItem() {
return false;
}
</script>
查看更多
查无此人
7楼-- · 2018-12-31 01:57

Set your button in normal way and use event.preventDefault like..

   <button onclick="myFunc(e)"> Remove </button>  
   ...
   ...

   In function...

   function myFunc(e){
       e.preventDefault();
   }
查看更多
登录 后发表回答