This function limits the number of checkboxes selected by the user, but I'm having trouble getting it to work when the name attribute has square brackets (i.e. name=baz[]
).
For some reason I can't get this code to work in jsfiddle, but it's based on this tutorial, which has a working demo.
function chkcontrol(j) {
var total = 0;
for (var i = 0; i < document.form1.baz.length; i++) {
if (document.form1.baz[i].checked) {
total = total + 1;
}
if (total > 3) {
alert("Please select up to three choices")
document.form1.baz[j].checked = false;
return false;
}
}
}
<form name="form1">
<input type=checkbox name="baz[]" value="1" onclick="chkcontrol(0);">Item 1
<input type=checkbox name="baz[]" value="2" onclick="chkcontrol(1);">Item 2
<input type=checkbox name="baz[]" value="3" onclick="chkcontrol(2);">Item 3
<input type=checkbox name="baz[]" value="4" onclick="chkcontrol(3);">Item 4
<input type=checkbox name="baz[]" value="5" onclick="chkcontrol(4);">Item 5
<input type=submit value="submit">
</form>