Search code examples
jqueryhtmlcheckboxhtml-selectdeselect

Why select/deselect checkbox works only once with jQuery?


I've a simple Select/Deselect option to check and uncheck checkboxes in my page. It works well, but only once. I don't know what's the problem for!
Please take a look at my codes. You can see its demo here.

HTML codes:

<input type="checkbox" id="main" />Select All<br />
<input type="checkbox" class="options" />Item 1<br />
<input type="checkbox" class="options" />Item 2<br />
<input type="checkbox" class="options" />Item 3<br />
<input type="checkbox" class="options" />Item 4<br />

jQuery code:

$('#main').click(function(e) {
    $('.options').attr('checked', this.checked);
});

Solution

  • You need to use .prop() instead of .attr()

    Use

    $('.options').prop('checked', this.checked);
    

    A Good Read .prop() vs .attr()