DIV CSS 佈局教程網

用 JS 判斷 checkbox 是否選中:逐項檢測與全選驗證
編輯:JavaScript基礎知識     

表單驗證中經常需要檢查勾選狀態,例如「哪些項目沒勾」或「一項都沒勾」。下面用幾段簡短的程式碼把常見需求都涵蓋起來。

需求一:找出第幾個沒有勾選

<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 在現代瀏覽器中已可迭代)。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved