Joyal
Joyal

Reputation: 2683

jquery checkbox become checked/unchecked one time, if I try again it doesn't work

Please check the fiddle

Here is the Code:

$(document).ready(function(){
        $('#main_chk').click(function(){    

            if(this.checked)
            {
                $(".chks").attr('checked', true);
            }
            else
            {
                $(".chks").removeAttr('checked');                                           
            }

        })
})

It works for the very first time (you have to click on the first check box) it will toggle the checkboxes, but if you try again,it doesn't works

Upvotes: 0

Views: 1782

Answers (4)

msm2020
msm2020

Reputation: 181

you can use :

$('#main_chk').mousedown(function() {
 if (!$(this).is(':checked')) {
     $(this).trigger("change");
 }
});

Upvotes: 0

Alexander
Alexander

Reputation: 23537

Use .change() and .prop() instead.

$(document).ready(function () {
    $('#main_chk').change(function () {
        if (this.checked) {
            $(".chks").prop('checked', true);
        } else {
            $(".chks").prop('checked', false);
        }
    });
});

Also, you can simplify it as follows.

$(document).ready(function () {
    $('#main_chk').change(function () {
        $(".chks").prop('checked', this.checked);
    })
})

See a live example here.

Note: The id attribute must be unique, please fix your HTML markup.

Upvotes: 3

bipen
bipen

Reputation: 36531

first..your html is invalid since you have more than one id with a same name... ID should always be unique.. change all your id to class..

secondly you can use prop();

 $('#main_chk').click(function(){   

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


 })

Upvotes: 0

Anujith
Anujith

Reputation: 9370

You can try this: http://jsfiddle.net/6bKyq/

 $(document).ready(function(){
    $('#main_chk').click(function(){    
        $(".chks").prop('checked', this.checked);
    });
 });

Upvotes: 1

Related Questions