JavaScript function EnableDisableChekboxes to set constraint of maximum allowed quantity checked checkboxes
There's a common constraint in votes or surveys like "choose no more than 3 items". And it's not a good idead to allow user control the checked items quantity. You can easily set constraint to a quantity of checked checkbox items with JavaScript and jQuery. You can just disable unchecked checkbox items if user checked maximum quantity and enables items again in case of unchecking.
I think it's a nice helpful solution. You can send array of IDs to function for actions.
The code of function here:
function EnableDisableChekboxes(ar) {
flag = 0;
maxChecked = 3;
for(i=0; i< ar.length; i++) {
if($(ar[i]).attr('checked') == 'checked') {
flag++;
}
}
if(flag >= maxChecked) { //disabling buttons if 3 items checked
for(i=0; i< ar.length; i++) {
if($(ar[i]).attr('checked') == 'checked') {
$(ar[i]).attr('checked', 'checked');
}
else {
$(ar[i]).attr('disabled', 'disabled');
}
}
}
if(flag < maxChecked) { //enabling buttons if less than 3 checked
for(i=0; i< ar.length; i++) {
if($(ar[i]).attr('checked') == 'checked') {
$(ar[i]).attr('checked', 'checked');
}
else {
$(ar[i]).removeAttr('disabled');
}
}
}
}
Usage of function:
arrayOfIds = [
"#ctl00_FormField1_ctl00_ctl00",
"#ctl00_FormField1_ctl00_ctl01",
"#ctl00_FormField1_ctl00_ctl02",
"#ctl00_FormField1_ctl00_ctl03",
"#ctl00_FormField1_ctl00_ctl04",
"#ctl00_FormField1_ctl00_ctl05",
"#ctl00_FormField1_ctl00_ctl06",
"#ctl00_FormField1_ctl00_ctl07"];
for(i=0; i< arrayOfIds.length; i++) {
$(arrayOfIds[i]).click(function() {
EnableDisableChekboxes(arrayOfIds);
});
}
I used this code for customization of SharePoint survey form and it was very good.

jQuery - check if checkbox element is checked
String functions to find Contains and to Replace in Javascript