DIV CSS 佈局教程網

限制核取方塊勾選數量:超過上限就自動停用其餘選項
編輯:關於JavaScript     

需求:頁面上有 10 個核取方塊,使用者最多只能勾 3 個;一旦勾滿,其餘未勾的方塊就變灰不可點;使用者取消勾選後,方塊又要恢復可用。把可變的部分(name 與上限)抽成函式參數,就能到處複用。

JS 函式

/**
 * 限制同名的核取方塊最多可勾選幾個
 * @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 不可重複:範例中每個 input 都寫 id="choice",HTML 規範要求 id 唯一,請刪掉多餘的 id 或改成 choice1、choice2…。
  • 事件綁在容器上:把 onclick 放在外層 div 靠冒泡捕捉,寫法簡短但語意不明;建議直接幫每個 checkbox 綁 change 事件。
  • disabled 會被停用的欄位不會送出:若表單後端需要知道「總共幾個選項」,記得改用 readonly 或另外搭配 hidden 欄位。
  • 更友善的做法:與其把方塊變灰,不如在超過上限時直接攔截並提示「最多只能選 3 項」,使用者才不會困惑為什麼點不動。
  • 無障礙:變灰的元件對螢幕閱讀器不友善,搭配 aria-disabled 與即時提示訊息會好很多。
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved