name=baz[]
这个函数限制了用户选择的复选框的数量,但是当 name 属性有方括号(即)时,我无法让它工作。
出于某种原因,我无法让这段代码在 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>