DIV CSS 佈局教程網

jQuery 統計複選框選中個數的示例
編輯:JQuery特效代碼     

以前用原生 JS 統計複選框選中數量時,只能先遍歷再判斷每個是否選中。改用 jQuery 後,這個過程可以變得非常簡潔。本文對比兩種實現方式。

原生 JavaScript 寫法

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<title>判斷複選框的選中個數</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
window.onload = function(){
  var btn = document.getElementById("btn");
  btn.onclick = function(){
  var arrays = new Array();
  var items = document.getElementsByName("check");
  for(i=0; i < items.length; i++){
   if(items[i].checked){ arrays.push(items[i].value); }
  }
  alert( "選中的個數為:"+arrays.length );
  }
}
</script>
</head>
<body>
<form method="post" action="#">
  <input type="checkbox" value="1" name="check" checked="checked"/>
  <input type="checkbox" value="2" name="check" />
  <input type="checkbox" value="3" name="check" checked="checked"/>
  <input type="button" value="你選中的個數" id="btn"/>
</form>
</body>
</html>

另一種遍歷統計寫法

在提交前先判斷是否有勾選,並給出相應提示:

<script Language="JScript">
function check(){
var boxArray = document.getElementsByName('oBox');
var total = 0;
for(var i=0;i<boxArray.length;i++){ if(boxArray[i].checked){ total++; } }
if(total>0){
  if(window.confirm('共選中'+total+'首歌,是否繼續?')){ window.open('about:blank','SubWin',''); return true; }
  else{ return false; }
}
else{ window.alert('沒有選擇!'); return false; }
}
</script>
<form target="SubWin" onsubmit="return check();">
<input type="checkbox" name="oBox">歌曲一
<input type="checkbox" name="oBox">歌曲二
<input type="checkbox" name="oBox">歌曲三
<input type="button" value="看看">
</form>

而如果使用 jQuery,則可以借助 size() 方法或 length 屬性,一行代碼就能取得選中項的數量,例如 $("input[name='check']:checked").length,無疑更加簡潔高效。

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