【问题标题】:Disabling submit button cancels submit event?禁用提交按钮会取消提交事件?
【发布时间】:2016-05-14 06:20:35
【问题描述】:

在我的客户端页面上,我在提交按钮上附加了一个监听器:

$(function() {                                                                  
  $('button[type="submit"]').click(submitButtonClicked);                      
});                                                                             

并且我想在单击按钮时禁用按钮和所有其他表单输入元素:

function submitButtonClicked(ev) {                                              
  if ($(this).hasClass('disabled')) {                                           
    return false; // Reject actions when disabled, preventDefault() and stopPropagation()                          
  }                                                                           
  $('form').find('input, select, textarea, button')                       
           .prop('disabled', true) // This call is the culprit?
           .blur();                                                       
  return true; // Submit form.
}                                                                               

上面的函数好像吞了事件,没有表单提交到达服务器。但是,如果我删除了prop('disabled', true),那么表单提交就好了,而且所有表单元素都保持启用和反应。

这是为什么呢?我假设返回 true 将导致事件 ev 继续传播,无论按钮是否被禁用。

【问题讨论】:

  • 与其禁用输入,不如将它们置于此处提到的只读状态:stackoverflow.com/questions/7730695/…。它应该很简单:$('form').find('input, select, textarea, button').prop('readonly', true).blur();。也许这会阻止用户更改内容但允许请求继续处理?...
  • 我不想将此作为答案发布,因为它并不能真正回答手头的问题。但是,作为一种解决方法,您可以将return true 替换为$('form').submit()。不再禁用按钮后,我得到的结果与您相同。我认为这是为了防止提交意外通过。

标签: javascript jquery forms


【解决方案1】:

由于按钮元素已被禁用,浏览器使用 disabled 属性来确定是否触发提交事件。请看下面的例子,点击事件被触发但表单没有提交

$("#button").click(function()
{
    console.log("disabling");
    $("#button").prop("disabled", true);
    console.log("disabled");
    return true;
});

$("#form").submit(function(){
    console.log("Submit");
});

$("#button").click();
$("#button").click();

【讨论】:

  • 所以事件确实传播了,但是浏览器取消了提交,因为现在禁用了submit按钮...?
  • 按照我的理解是的
  • 你是对的,根据this thread :)
  • 我没有编辑它,但 html 上的正常点击事件仍然会在两次点击调用中触发
【解决方案2】:

在 form.submit 之后禁用您的表单。

...
setTimeout(function(){
    $('form').find('input, select, textarea, button')                       
       .prop('disabled', true);}, 200);//setTimeout
return true;

【讨论】:

    【解决方案3】:

    改变

    $('form').find('input, select, textarea, button')
    

    $('form').find('input:not([type=submit]), select, textarea, button')
    

    【讨论】:

    • 可能再看看问题:他使用的是button ;)
    • 这不包括禁用提交按钮。这是否意味着禁用submit 按钮会取消表单?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-11
    • 2016-04-03
    • 1970-01-01
    • 2011-01-08
    • 2018-06-30
    • 1970-01-01
    相关资源
    最近更新 更多