需求:頁面上有 10 個核取方塊,使用者最多只能勾 3 個;一旦勾滿,其餘未勾的方塊就變灰不可點;使用者取消勾選後,方塊又要恢復可用。把可變的部分(name 與上限)抽成函式參數,就能到處複用。
/**
* 限制同名的核取方塊最多可勾選幾個
* @param name 核取方塊的 name
* @param num 最多允許勾選的數量
*/
function choicetest(name, num) {
var choicearr = document.getElementsByName(name);
var a = 0;
// 先統計已勾選數量
for (var i = 0; i < choicearr.length; i++) {
if (choicearr[i].checked) a++;
}
if (a == num) {
// 勾滿了:停用所有未勾的
for (var i = 0; i < choicearr.length; i++) {
if (!choicearr[i].checked) choicearr[i].disabled = 'disabled';
}
} else {
// 未勾滿:全部恢復可用
for (var i = 0; i < choicearr.length; i++) {
choicearr[i].removeAttribute('disabled');
}
}
}
<!DOCTYPE html>
<html>
<head><meta charset="utf-8"><title>核取方塊數量限制</title></head>
<script type="text/javascript">
function choicetest(name, num) {
var choicearr = document.getElementsByName(name);
var a = 0;
for (var i = 0; i < choicearr.length; i++) if (choicearr[i].checked) a++;
if (a == num) {
for (var i = 0; i < choicearr.length; i++)
if (!choicearr[i].checked) choicearr[i].disabled = 'disabled';
} else {
for (var i = 0; i < choicearr.length; i++)
choicearr[i].removeAttribute('disabled');
}
}
</script>
</head>
<body>
<div onclick="choicetest('choice', 3)">
<label><input type="checkbox" name="choice"> 選擇1</label>
<label><input type="checkbox" name="choice"> 選擇2</label>
<label><input type="checkbox" name="choice"> 選擇3</label>
<label><input type="checkbox" name="choice"> 選擇4</label>
<label><input type="checkbox" name="choice"> 選擇5</label>
<p></p>
<label><input type="checkbox" name="choice"> 選擇6</label>
<label><input type="checkbox" name="choice"> 選擇7</label>
<label><input type="checkbox" name="choice"> 選擇8</label>
<label><input type="checkbox" name="choice"> 選擇9</label>
<label><input type="checkbox" name="choice"> 選擇10</label>
</div>
</body>
</html>
id="choice",HTML 規範要求 id 唯一,請刪掉多餘的 id 或改成 choice1、choice2…。aria-disabled 與即時提示訊息會好很多。