jQuery to check and uncheck checkboxes only fires once

checkbox, javascript, jquery

Solution

Change your `.attr()` to `.prop()`.

$('#all').on('change', function() {
    if (!$(this).is(':checked')) {
        $('.country').prop('checked', false);   
    } else {
        $('.country').prop('checked', true);
    }
});    
$('#none').on('change', function() {
    if (!$(this).is(':checked')) {
        $('.country').prop('checked', true);    
    } else {
        $('.country').prop('checked', false);
    }
});

jsFiddle example

You could also reduce this to just:

$('#all').on('change', function () {
    $('.country').prop('checked', $(this).is(':checked'));
});
$('#none').on('change', function () {
    $('.country').prop('checked', !$(this).is(':checked'));
});

jsFiddle example

As the docs for .attr() state:

As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set. To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the .prop() method.

Problem

I have a very simple requirement for my jQuery: to check a set of boxes if a radio button is checked, and to clear them all if another is checked. The jquery works, however it only works once - that is if I click to check them all (all boxes check) and then click to clear them (all boxes clear), and then again click to check them all - there is no effect. Similarly if I manually uncheck some boxes then click to select all again, there is no effect. jQuery ``` $('#all').on('change', function() { if (!$(this).is(':checked')) { $('.country').attr('checked', false); } else { $('.country').attr('checked', true); } }); $('#none').on('change', function() { if (!$(this).is(':checked')) { $('.country').attr('checked', true); } else { $('.country').attr('checked', false); } }); ``` HTML ``` <div class="subselect"> <input type="radio" class="TLO" name="radio1" id="all" />Check All <br /> <input type="radio" class="TLO" name="radio1" id="none" />Clear All <br /> </div> <br /> <br /> <div class="cselect" id="countries"> <input type="checkbox" class="country" />1 <br /> <input type="checkbox" class="country" />2 <br /> <input type="checkbox" class="country" />3 </div> ``` jsFiddle http://jsfiddle.net/vsGtF/1/

Original source