この関数は、ユーザーが選択するチェックボックスの数を制限しますが、name 属性に角かっこ (つまりname=baz[]
) があると機能しません。
何らかの理由で、このコードを jsfiddle で動作させることはできませんが、このチュートリアルに基づいており、動作するデモがあります。
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>