Ovi
Ovi

Reputation: 2559

check/uncheck all checkboxes

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?

Upvotes: 3

Views: 5205

Answers (4)

andrean
andrean

Reputation: 107

You can try with this

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

Upvotes: 0

roselan
roselan

Reputation: 3775

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);
});

Upvotes: 0

codeandcloud
codeandcloud

Reputation: 55200

Keep it simple. Try this

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

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

Upvotes: 7

Alex Turpin
Alex Turpin

Reputation: 47776

Try filtering out the checkbox in your selectors.

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

Upvotes: 2

Related Questions