Select All/Deselect All checkboxes in a page
If using jquery, you can use the following (coffeeScript):
if (this.checked)
$(':checkbox').each ->
$(this).prop('checked', true)
else
$(':checkbox').each ->
$(this).prop('checked', false)
I found an issue trying to set this.checked = false - not really sure what was happening, but the above code worked.
Here's a working example for you: http://jsfiddle.net/wYPWL/
HTML example:
<input type="checkbox" id="selectAll" value="selectAll"> Select / Deselect All<br/><br/>
<input type="checkbox" name="foo" value="bar1"> Bar 1<br/>
<input type="checkbox" name="foo" value="bar2"> Bar 2<br/>
<input type="checkbox" name="foo" value="bar3"> Bar 3<br/>
<input type="checkbox" name="foo" value="bar4"> Bar 4<br/>
Javascript:
$('#selectAll').click(function() {
if (this.checked) {
$(':checkbox').each(function() {
this.checked = true;
});
} else {
$(':checkbox').each(function() {
this.checked = false;
});
}
});
This will work regardless of what your checkboxes are named. If you really wanted to target only your checkboxes shown in your code above, you can replace $(':checkbox')
with $('input[id^="distribution_ids"]')
which is jQuery's way of targeting input elements that have an ID that starts with distribution_ids
I have found an issue with iWasRobbed's Answer that if Select All
is checked and then if you unchecked any one option like (Bar1
, Bar2
, Bar3
) then Select All
must be unchecked...
Here is Solution..
HTML Code
<input id="campaign_range_ids_1" class="checkbox" type="checkbox" value="1" name="campaign[range_ids][]"> India
<input id="campaign_range_ids_2" class="checkbox" type="checkbox" value="2" name="campaign[range_ids][]"> London
<input id="campaign_range_ids_3" class="checkbox" type="checkbox" value="3" name="campaign[range_ids][]"> USA
<input id="campaign_range_ids_4" class="checkbox" type="checkbox" value="4" name="campaign[range_ids][]"> All
JavaScript Code:
$('#campaign_range_ids_4').click(function () {
if ($(this).is(':checked')) {
$('#campaign_range_ids_1,#campaign_range_ids_2,#campaign_range_ids_3').prop('checked', true);
} else {
$('#campaign_range_ids_1,#campaign_range_ids_2,#campaign_range_ids_3').prop('checked', false);
}
});
$('#campaign_range_ids_1,#campaign_range_ids_2,#campaign_range_ids_3').click(function () {
if ($(this).is(':checked')) {
} else {
$('#campaign_range_ids_4').prop('checked', false);
}
});