DEV Community

Syed Saadullah Shah
Syed Saadullah Shah

Posted on

Mootools Function for Limiting Number of Checkboxes Checked

Here’s a handy function for controlling how many boxes can be checked in a group of checkboxes. Consider the following html:

Category 1
Category 2
Category 3

To impose the maximum, apply the following Mootools function on domready:

var total = 0;
$$('.catchk').each(function(el){
el.addEvent('change',function(){
total = (this.checked == true) ? total + 1 : total - 1;
if(total > 2){
alert("Please choose a maximum of 2 categories")
this.checked = false ;
total = total - 1;
}
return false;
})
})

Simple, yet effective. Bear in mind that this is a client-side check, as is all Javascript validation, so in order to protect the integrity of your data, you must validate on the server side as well. Consider this type of Javascript validation to be only a courtesy to your users. It improves usability, but does not control what is sent to the processing script.

Discussion (0)