Very often we need to present many checkboxes, and there is one additional checkbox for select-all. The html code is somewhat like the following:
Select All
1
2
3
4
Notice I name the js function toggle_selection because you may actually make it toggle later on.
Then, to enable the usual select-all action, this is the code:
function toggle_selection(){
$("input[name='opt[]']").each(function (index, el)
{
if ($("#my_select_all").is(":checked")) $(el).attr("checked", "checked");
});
}
Straightforward.
If you want to make the select-all checkbox toggle, change the if statement to the following:
if ($("#my_select_all").is(":checked")) $(el).attr("checked", "checked");
else $(el).removeAttr("checked");
Now, how do we disallow the de-select when select-all is checked? No problem, jQuery to the rescue!
jQuery().ready(function (){
$("input[name='opt[]']").each(function(index, el) {
$(this).change(function(){
if ($("#my_select_all").is(":checked")) $(el).attr("checked", "checked");
});
});
}
We are binding a onChange callback to each checkbox. Upon clicking, if our select-all checkbox is checked, our current checkbox will always be set to checked.
Don’t you love jQuery?