如何防止按钮提交表单 [英] How to prevent buttons from submitting forms

查看:23
本文介绍了如何防止按钮提交表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在接下来的页面中,使用 Firefox,删除按钮提交表单,但添加按钮不提交.

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

如何防止 remove 按钮提交表单?

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>

推荐答案

您正在使用 HTML5 按钮元素.请记住原因是此按钮具有提交的默认行为,如 W3 规范中所述,如下所示:W3C HTML5 按钮

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.

这篇关于如何防止按钮提交表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆