【问题标题】:Toggle enable/disable input button if one or more checkboxes are checked [duplicate]如果选中一个或多个复选框,则切换启用/禁用输入按钮[重复]
【发布时间】:2013-07-15 14:36:07
【问题描述】:

我有一小段代码想用作 jQuery 对话框的条件。非常简单的情况,如果选中了复选框,则启用按钮,如果没有,则禁用它。下面的代码很好地禁用了按钮,但在检查任何复选框时都没有启用它。

我尝试了多种变体,但无法让它在我的代码中工作(在 Fiddle 中有几个工作正常)。非常感谢您的帮助。

JS sn-p

if (button.text() == "Apply") {
    if ($("selectLocation").is(':checked'))
        button.enabled(true); // checked
    else
        button.enabled(false);  // unchecked
}

HTML

<input type="checkbox" name="selectLocation" />

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    你将不得不使用 Jquery 的 .prop() 来解决这个问题

    if (button.text() == "Apply"){
        if ($("selectLocation").is(':checked')){
            button.prop('disabled', false);
        }
        else{
            button.prop('disabled', true);
        }
    }
    

    我从来没有让 .attr() 在这种情况下工作

    【讨论】:

    • 非常感谢您的出色解决方案!
    【解决方案2】:

    试试这样:

    $("input[name=selectLocation]")
    

    它不起作用,因为您选择的是标签为 selectLocation 的元素,而不是名称为 selectLocation 的元素

    【讨论】:

      【解决方案3】:

      如果按钮是 jquery 元素:

      button.attr("disabled", "disabled"); //to disable it
      button.removeAttr("disabled"); //to reenable it
      

      在您的代码中,它应该是:

      if (button.text() == "Apply") {
          if ($("selectLocation").is(':checked'))
              button.removeAttr("disabled"); //to reenable it
          else
              button.attr("disabled", "disabled");
      }
      

      选择器$("input[name=selectLocation]") 应该可以工作

      【讨论】:

        【解决方案4】:

        不确定 jQuery 是否会选择这样的名称,添加一个 ID 并更改选择器。

        if (button.text() == "Apply") {
            if ($("#selectLocation").is(':checked'))
                button.removeAttr("disabled");
            else
                button.attr("disabled", "disabled");
        }
        
        <input id="selectLocation" type="checkbox" name="selectLocation" />
        

        【讨论】:

          猜你喜欢
          • 2021-11-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-01-08
          • 1970-01-01
          • 1970-01-01
          • 2015-09-22
          • 1970-01-01
          相关资源
          最近更新 更多