选择单个复选框时如何选中所有复选框

时间:2014-02-13 10:04:18

标签: jquery

您好

在选择单个复选框时尝试选中所有复选框时出现问题。 这些是动态生成的(通过AJAX)复选框,因此绑定事件有些繁琐。以下是html中的代码

<form id="frm" name="frm">
    <input name="chk" type="checkbox" id="chk" value="" />main checkbox
    <input name="chk1" type="checkbox" id="chk1" value="" />1
    <input name="chk2" type="checkbox" id="chk2" value="" />2
    <input name="chk3" type="checkbox" id="chk3" value="" />3
    <input name="chk4" type="checkbox" id="chk4" value="" />4
    <input name="chk5" type="checkbox" id="chk5" value="" />5
    <input name="chk6" type="checkbox" id="chk6" value="" />6
</form>

3 个答案:

答案 0 :(得分:3)

您可以使用$(this).prop('checked')

而不是this.checked
$(document).ready(function() {
    $("#sub").on("click", "#chk" , function() {      
        var checkboxes = $(this).closest('form').find(':checkbox');
        checkboxes.prop('checked', this.checked);
    });
});

答案 1 :(得分:2)

尝试

jQuery(function ($) {
    $('#chk').change(function () {
        $('#frm input[type="checkbox"]').not(this).prop('checked', this.checked)
    })
})

演示:Fiddle

答案 2 :(得分:0)

$(document).ready(function () {
    $("body").on("click", "#chk", function () {
        var checkboxes = $(this).closest('form').find(':checkbox');
        checkboxes.prop('checked', $(this).prop('checked'));
    });
}); 

如果单击“chk”复选框,它将起作用,它将检查该表单中的所有复选框, 即使它们是通过Ajax加载的

相关问题