Limit checkbox selection with jQuery
At some point you may come across a situation where you need a user to select a set number of options from a group of checkboxes, in this case a radio group may not be suitable
In my example I needed only one checkbox to be selected, now why did I not use a radio group? Well these checkboxes are generated by Joomla in its table layouts, they are used to store row ids so that functions such as deletion, publishing etc can be performed quickly on them. The following code allows you to limit the number of checkboxes a user can select from a list, or table depending on your situation.
jQuery('input[name=cid[]]').click(function () {
selected = jQuery('input[name=cid[]]').filter(':checked').length;
if (selected > 1) {
jQuery('input[name=cid[]]').each(function () {
jQuery(this).attr('checked', false);
});
jQuery(this).attr('checked', true);
}
});
You can see that we get all the checkboxes with the same name, in this case an array of ids. We then get the number of selected items with the length command, from then on you can set the number you wish to limit to and then perform any functionality you require. Here i’ve simply unchecked all other checkboxes so that only one at a time can be selected.