Limit checkbox selection

Is there any way to limit checkbox selection?

If I have five choices for the checkboxes, I don’t want someone to check more than 3.  After a third box is selected, I want the other unchecked boxes to be disabled.  If any of the checked boxes are unchecked, then enable the disabled boxes.

Any direction on how this can be done?

 

I created a javascript that defines a function that checks the numbers of items selected and prevents it from going over a max amount.  I declared that script in the "Before Fields" section of the "Customize HTML" tab of the form.

Then I added an action hook for frm_field_input_html that outputs 'onclick=function()' for the specific checkbox field.  Looking at the source code of the webpage, I can see the html was generated correctly, but it's not working.

Am I heading in the right direction?

 

Never mind.  Figure it out.

Let me know if you want me to put the javascript code to check for the limit.

Sure, posting it could be helpful. This question has come up once or twice In the past.

You could let me know if you see anything wrong with it.

function limit_ckbox(obj,max)
{
var cnt=0;
var cbfield=document.getElementsByName(obj.name);
for (var i=0; i cnt += cbfield[i].checked;
}
if (cnt > max) {
obj.checked = false;
}
}

This code does not error anything, it just doesn't allow anymore things to be checked if it has already reached a limit.

In the frm_field_input_html hook, put
echo 'onclick="limit_ckbox(this, 3)"';
where 3 is the limit of the check box selection.

Thanks for sharing!

Topic closed.