check/uncheck all checkboxes

£可爱£侵袭症+ 提交于 2019-12-02 01:11:12

问题


I am trying to have a checkbox that checks/unchecks all the other checkboxes.

I am using this code:

$("#checkall").toggle(   
    function () {
        $(".kselItems").attr('checked', 'checked');
    },
    function () {
        $(".kselItems").removeAttr("checked"); 
});

This works fine, but for some reason, the checkbox with the id checkall (the one that should make every thing work) never stays checked.

How can this be fixed?


回答1:


Keep it simple. Try this

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

Demo: http://jsfiddle.net/naveen/azkPR/




回答2:


Try filtering out the checkbox in your selectors.

        $("#checkall").toggle(   
            function () {
                $(".kselItems:not(#checkall)").attr('checked', 'checked');
            },
            function () {
                $(".kselItems:not(#checkall)").removeAttr("checked"); 
        });



回答3:


edit: while I writed, xeno06 answered too :)

when you click "checkall", it 1) set the value to checked, and then 2) call the toggle function, which will find "checkall", and toogle it back.

best way is to not put the ".kselItems" class to "checkAll" or, if "checkall" is inside ".ksleItems" use

$(".kselItems not(#checkall)").(...)

or

$(".kselItems").not("#checkall").(...)

for clarity I would use naveen solution

$("#checkall").click(function() {
    $(".kselItems :checkbox").not("#checkall").attr('checked', this.checked);
});



回答4:


You can try with this

$("#checkall").click(function() {
   $(".kselItems").prop('checked', this.checked);
});


来源:https://stackoverflow.com/questions/7095039/check-uncheck-all-checkboxes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!