Disallow de-select when select-all is checked

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

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");


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) {
			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?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s