如果选中一个或多个复选框,则切换启用/禁用输入按钮

时间:2013-07-15 14:36:07

标签: javascript jquery

我有一小段代码要用作jQuery对话框的条件。非常简单的情况,如果选中复选框,则启用按钮,否则禁用它。以下代码禁用该按钮就好了,但在选中任何复选框时都不启用它。

我尝试了多种变体,我无法在我的代码中使用它(在Fiddle中可以正常工作)。非常感谢你的帮助。

JS代码段

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

HTML

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

4 个答案:

答案 0 :(得分:2)

你必须使用Jquery的.prop()来解决这个问题

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

我从来没有能够让.attr()为这种情况工作

答案 1 :(得分:0)

试试这样:

$("input[name=selectLocation]")

它无效,因为您选择的标记为selectLocation的元素不是名为selectLocation的元素

答案 2 :(得分:0)

如果button是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]")应该可以正常工作

答案 3 :(得分:0)

不确定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" />