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条回答
伤终究还是伤i
2楼-- · 2018-12-31 01:58

Here's a simple approach:

$('.mybutton').click(function(){

    /* Perform some button action ... */
    alert("I don't like it when you press my button!");

    /* Then, the most important part ... */
    return false;

});
查看更多
弹指情弦暗扣
3楼-- · 2018-12-31 01:59

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

=)

查看更多
梦该遗忘
4楼-- · 2018-12-31 02:01

I'm not able to test this right now, but I would think you could use jQuery's preventDefault method.

查看更多
查无此人
5楼-- · 2018-12-31 02:01

The function removeItem actually contains an error, which makes the form button do it's default behaviour (submitting the form). The javascript error console will usually give a pointer in this case.

Check out the function removeItem in the javascript part:

The line:

rows[rows.length-1].html('');

doesn't work. Try this instead:

rows.eq(rows.length-1).html('');
查看更多
登录 后发表回答