【问题标题】:how to disable multiple form buttons on form submit and still have correct action performed如何在表单提交上禁用多个表单按钮并仍然执行正确的操作
【发布时间】:2012-01-27 18:51:48
【问题描述】:

我有一个带有多个提交按钮的表单。我只想在按下其中任何一个后禁用它们,并且一切正常,直到我在 .submit() JQuery 处理程序中“禁用”它们,在这种情况下,表单不再显示与表单一起发送按钮名称/值信息.如何禁用按钮但仍提交按钮名称/值,以便确定按下了哪个按钮?

表格

<form action="myaction" method="post" name="sendgift" id="sendgift" > 
    ....input, etc ....       
    <input type="submit" name="_action_go" value="Looks great! Do it" id="sendgiftbtn" />
    <input type="submit" name="_action_index" value="I need to make changes" id="gobackbtn" />
</form>

JS:

<script type="text/javascript">
    $("#sendgift").submit(function() {

       //if I remove these two lines, everything works
       $("#sendgiftbtn").attr('disabled', 'disabled');
       $("#gobackbtn").attr('disabled', 'disabled');

        console.log("disable buttons called");
        return true;
    });


</script>

【问题讨论】:

    标签: jquery html forms


    【解决方案1】:

    disabled 属性通过设计从表单提交中删除元素:http://www.w3schools.com/tags/att_input_disabled.asp

    3 种方法:

    1. 如果你想让它“显示”表单元素被禁用 您可以让 js 将字段的值存储在隐藏变量中 <input type='hidden' value='[the value of the disabled field]' name='[name of disabled field]' /> 然后禁用可见 输入。

    2. 您还可以尝试将该字段设置为禁用,并添加一个 onfocus 事件,以便在用户尝试再次修改该字段时blur()s 该字段。

    3. 您可以将 onsubmit 事件添加到取消禁用任何 具有禁用属性集的输入,以便它们被提交 照常。

    【讨论】:

    • +1,重要的是要注意这种行为是 HTML 设计的,而不是 jQuery 特定的。
    【解决方案2】:

    在这种情况下,不要禁用按钮,而是添加 disabled 类,并在您 submit form 时检查此类。如果该类仅存在return false,否则true 并在返回true 之前将disabledclass 添加到buttons 类型的所有buttonssubmit

     $("#sendgift").submit(function(e) {
    
            if(!$(e.target).hasClass('disabled')){
                //if I remove these two lines, everything works
                //$("#sendgiftbtn").attr('disabled', 'disabled');
                //$("#gobackbtn").attr('disabled', 'disabled');
    
                //console.log("disable buttons called");
    
                $(this).find('input[type=submit]').addClass('disabled');
    
                return true;
            }
            return false;
        });
    

    disabled按钮样式定义为

    .disabled{
      padding: 0px 6px 0px 6px;
      border: 2px outset ButtonFace;
      color: GrayText;
      cursor: inherit;
    }
    

    【讨论】:

    • 这不会改变按钮的外观。
    • 您可以通过在disabled 类中设置样式来使按钮看起来禁用。我已将所需的样式添加到我的答案中,希望对您有所帮助。
    • 啊,这更有意义。谢谢。
    • 如果对您有帮助,请将其标记为答案
    • 最终选择了这个解决方案。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-07
    • 2013-08-19
    • 1970-01-01
    • 2020-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多