找到提交表单的所有提交按钮

时间:2016-04-22 21:59:12

标签: javascript jquery html forms

我试图在提交表单时禁用表单的所有提交类型元素,以避免双击。但我只希望禁用提交表单中的按钮。

例如,点击Submit按钮时,只应禁用Submit按钮和Another submit to disable (same form)。其他提交元素应保持原样。

以下代码会禁用所有提交元素。

$(document).on('submit', function (event) {
    event.preventDefault();
 
    var submit_button = $(':submit');
    submit_button.prop('disabled', true);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button type="submit">Not part of submitted form (leave enabled)</button>
<form>
  <input type="text">
  <button type="submit">Part of another Form (leave enabled)</button>
</form>

<form>
  <input type="text">
  <button type="submit">Submit</button>
  <button type="submit">Another submit to disable (same form)</button>
</form>

2 个答案:

答案 0 :(得分:2)

好吧,event.target会引用submited form,因此您可以使用submit buttons选择器在该表单中找到所有:submit:< / p>

$(document).on('submit', function (event) {
    event.preventDefault();              
    $(':submit',event.target).prop('disabled', true);

});

检查以下代码段示例

$(document).on('submit', function(event) {
  event.preventDefault();
  $(':submit', event.target).prop('disabled', true);

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="submit">Not part of submitted form (leave enabled)</button>
<form>
  <input type="text">
  <button type="submit">Part of another Form (leave enabled)</button>
</form>

<form>
  <input type="text">
  <button type="submit">Submit</button>
  <button type="submit">Another submit to disable (same form)</button>
</form>

答案 1 :(得分:0)

检测表单提交,然后在该表单中搜索按钮[type = submit]并禁用它们。

$('form').on('submit', function (event) {
    event.preventDefault();

    var submit_button = $(this).find('button[type="submit"]');
    submit_button.prop('disabled', true);
});