jquery统计复选框选中示例

  以前我使用js只能判断遍历再获取

  

复制代码 代码如下:

  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <html xmlns="http://www.w3.org/1999/xhtml">

  <head>

  <title>jQuery判断复选框的选中个数</title>

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

  <script type="text/javascript">

  window.onload = function(){//页面所有元素加载完毕

  var btn = document.getElementById("btn");  //获取id为btn的元素(button)

  btn.onclick = function(){  //给元素添加onclick事件

  var arrays = new Array();   //创建一个数组对象

  var items = document.getElementsByName("check");  //获取name为check的一组元素(checkbox)

  for(i=0; i < items.length; i++){  //循环这组数据

  if(items[i].checked){      //判断是否选中

  arrays.push(items[i].value);  //把符合条件的 添加到数组中. push()是javascript数组中的方法.

  }

  }

  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>

  通过jQuery获取checkbox选中项的个数,需要用到jQuery的size()方法或length属性,下面的例子是通过length属性获得checkbox选中项的个数。

  

复制代码 代码如下:

  <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>