jquery:check all / none复选框只能运行一次

时间:2013-08-16 11:27:38

标签: jquery html

我正在检查all / none复选框。但是,它只能运行一次:它可以检查所有,然后取消选中所有,但不能再检查它们。

http://jsfiddle.net/SDEwB/

check all/none: <input type = "checkbox" id = "check_all_none"></input>
<br/>
<input type = "checkbox" class = "others"></input><br/>
<input type = "checkbox" class = "others"></input>


$('#check_all_none').change(function () {
    if ( $(this).is(':checked') ){
        $('.others').attr("checked", true);
    }
    else{
        $('.others').removeAttr("checked"); 
       // $('.others').attr("checked", false); // tried this, too
    }
});

5 个答案:

答案 0 :(得分:6)

使用

$('#check_all_none').change(function () {
    $('.others').prop("checked", this.checked);
});

演示:Fiddle

答案 1 :(得分:4)

试试这个

 $('#check_all_none').click(function () {
if ( $(this).is(':checked') ){
    $('.others').prop("checked", true);
}
else{
    $('.others').removeAttr("checked");
 }

});

Demo

答案 2 :(得分:1)

使用prop代替attr。

if ( $(this).is(':checked') ){
    $('.others').prop("checked", true);
}
else{
    $('.others').prop("checked", false);
}

http://jsfiddle.net/SDEwB/3/

<强>更新

像阿伦说的那样,这更好:

$('#check_all_none').change(function () {
    $('.others').prop("checked", this.checked);
});

答案 3 :(得分:0)

这是检查所有想要的复选框的简单方法:

$("#check_all_none").click(function() {
    $(".others").attr('checked', this.checked);
});

DEMO

答案 4 :(得分:0)

<input type = "checkbox" id = "check_all_none" onclick="checkAll(this)" />
<input type = "checkbox" class = "others" name="chk" /><br/>
<input type = "checkbox" class = "others" name="chk" /> 

<强> JQuery的:

function checkAll(t){
    if ( $(t).is(':checked') ){
        $('.others').prop("checked", true);
    }
    else{
        $('.others').attr('checked', false);
    }   
}

<强> JavaScript的:

function checkAll(t){
   var checkboxes= document.getElementsByName('chk');
    for (var i = 0; i < checkboxes.length; i++) {
        if(t.checked==true){
            checkboxes[i].checked = true;
        }else{
            checkboxes[i].checked = false;
        }
    }
}

我已声明功能。因为您可以轻松地在任何地方重用此代码。我编写了两种类型的代码(JQuery和JavaScript)。两者都很好。如果您不需要使用任何jQuery库,那么请使用JavaScript代码。

相关问题