表單驗證中經常需要檢查勾選狀態,例如「哪些項目沒勾」或「一項都沒勾」。下面用幾段簡短的程式碼把常見需求都涵蓋起來。
<input type="checkbox" name="checkbox1" checked>
<input type="checkbox" name="checkbox1">
<input type="checkbox" name="checkbox1" checked>
<input type="checkbox" name="checkbox1">
<input type="checkbox" name="checkbox1">
<script language="javascript">
function check(obj)
{
for(i = 0; i < document.all(obj).length; i++)
{
if(!document.all(obj)[i].checked) alert("第" + (i+1) + "個沒有選擇")
}
}
</script>
<input type="button" onclick="check('checkbox1')" value="檢測">
<input type="checkbox" name="test">
<input type="checkbox" name="test">
<input type="checkbox" name="test">
<input type="checkbox" name="test">
<input type="checkbox" name="test">
<script language="JavaScript">
function check(obj){
for(i = 0; i < document.all(obj).length; i++){
if(document.all(obj)(i).checked){
return;
}
}
window.alert('一個也沒有選!');
}
</script>
<input type="button" onclick="check('test');" value="檢測">
這段的邏輯是「找到任何一個已勾選就立刻 return」,迴圈跑完都沒 return,就代表全未勾選。
上面範例依賴 document.all,這是非標準且已被淘汰的 API。實際專案中建議改用標準選擇器:
// 取得所有 name 為 test 的 checkbox
var boxes = document.querySelectorAll('input[name="test"]');
// 逐項檢測
boxes.forEach(function(box, i){
if(!box.checked) console.log("第" + (i+1) + "個沒有選擇");
});
// 是否一項都沒勾
var checkedCount = document.querySelectorAll('input[name="test"]:checked').length;
if(checkedCount === 0){
alert('一個也沒有選!');
}
// 是否全選
if(checkedCount === boxes.length){
console.log('已全部勾選');
}
用 :checked 偽類別直接篩選已勾選項,比迴圈遍歷更直觀;若要轉為陣列以使用 map/filter,可以寫成 Array.prototype.slice.call(boxes),或直接 [...boxes](NodeList 在現代瀏覽器中已可迭代)。