【问题标题】:Disable submit button with text input and select dropdown禁用带有文本输入的提交按钮并选择下拉菜单
【发布时间】:2014-06-04 03:54:58
【问题描述】:

我正在尝试禁用提交按钮,直到所有字段都有值。它适用于电子邮件和密码输入,但不适用于选择下拉菜单。

我知道这是由于.keyup() 未应用于下拉菜单,但不确定如何调整代码。我已经尝试使用 change() 事件,但它完全禁用了提交按钮。

<form>   
    <input class="disableButton" id="email" type="email" />         
    <input class="disableButton" id="pass" type="password" />
    <select id="state" class="selected-state disableButton">
        <option value="">State</option>
        <option value="AL">AL</option>
        <option value="AK">AK</option>
        ...
    </select>
    <input id="emailPassSubmit" type="button" disabled="disabled" />
</form>

<script>
$(function() {
    $('.disableButton').keyup(function() {
        if ($('#email').val() == '' || $('#pass').val() == '' ||  $('#state').val() == '') {
            $('#emailPassSubmit').prop('disabled', true);
        } else {
            $('#emailPassSubmit').prop('disabled', false);
        }
    });
});
</script>

【问题讨论】:

    标签: jquery submit disabled-input


    【解决方案1】:

    您需要测试keyup()change() 事件,因为您想在不同类型的元素上触发它。

    您可以使用 jQuery 的 on() 方法将多个事件附加到元素,如下所示:

    $('.disableButton').on('keyup change', function(){ ...
    

    jsFiddle here

    【讨论】:

    • 就是这样!谢谢,空
    【解决方案2】:

    您忘记将 disableButton 类添加到选择下拉列表中。

    这是一个工作版本:

    http://jsbin.com/gonut/1/

    【讨论】:

      【解决方案3】:

      所选答案有效,但不优雅或可扩展。出于某种原因,每个字段都是硬编码的,即使您已经为每个必需的输入添加了一个类也很麻烦。

      相反,只需使用“.disableButton”类循环遍历每个项目:

      $('.disableButton').on('keyup change', function() {
          var empty = false;
          $('.disableButton').each(function() {
              if ($(this).val() == '') {
                  empty = true;
              }
          });
      
          if (empty) {
              $('#emailPassSubmit').prop('disabled', true);
          } else {
              $('#emailPassSubmit').prop('disabled', false);
          }
      });
      

      只需确保每个字段(适用于文本输入、下拉菜单等)都有“disableButton”类。此外,下拉菜单必须具有默认值“”,您的默认值就是这样。

      这样,将来你可以添加任意数量的字段,只要你有正确的类,你就完全不用接触这段代码了。

      【讨论】:

        猜你喜欢
        • 2021-05-13
        • 2011-03-25
        • 2020-10-18
        • 2021-09-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-10-18
        • 1970-01-01
        相关资源
        最近更新 更多