日期:2014-05-16  浏览次数:20317 次

JS jQuery分别获取选中的复选框值
今天看了一下流量统计,发现很多朋友都在搜索“获取选中的复选框的值”,由于很多朋友不使用jquery,而jquery又特别的方便,所以决定写一篇JavaScript和jQuery分别获取选中的复选框值,下面请看HTML代码部分,
在线演示

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<style>

</style>
<title>JS获取复选框被选中的值</title>
</head>
<body>
<input type="checkbox" name="aihao" value="0" />0&nbsp;&nbsp;
<input type="checkbox" name="aihao" value="1" />1&nbsp;&nbsp;
<input type="checkbox" name="aihao" value="2" />2&nbsp;&nbsp;
<input type="checkbox" name="aihao" value="3" />3&nbsp;&nbsp;
<input type="checkbox" name="aihao" value="4" />4&nbsp;&nbsp;
<input type="checkbox" name="aihao" value="5" />5&nbsp;&nbsp;
<input type="checkbox" name="aihao" value="6" />6&nbsp;&nbsp;
<input type="checkbox" name="aihao" value="7" />7&nbsp;&nbsp;
<input type="button" onclick="chk()" value="提  交" />
</body>
</html> 总共有八个checkbox和一个按钮,点击“提交”按钮后可以知道当前所选中的复选框的value值,下面是JS代码,
<script src="jquery.js"></script><!--这是载入jquery.js文件,如果不使用jquery可以去掉-->
<script>
function chk(){
  var obj=document.getElementsByName('aihao');  //选择所有name="aihao"的对象,返回数组
  //取到对象数组后,我们来循环检测它是不是被选中
  var s='';
  for(var i=0; i<obj.length; i++){
    if(obj[i].checked) s+=obj[i].value+',';  //如果选中,将value添加到变量s中
  }
  //那么现在来检测s的值就知道选中的复选框的值了
  alert(s==''?'你还没有选择任何内容!':s);
}

function jqchk(){  //jquery获取复选框值
  var s='';
  $('input[name="aihao"]:checked').each(function(){
    s+=$(this).val()+',';
  });
  alert(s==''?'你还没有选择任何内容!':s);
}
</script> 点击“提交”后,可以得到正确的选择值了,但是后面多一个,(英文逗号),这个可以检测一下再用substring去除,或者获取到复选框选择值后一般都要转成数组再使用的,所以也可以在转成数组后,去除最后一个数组元素。

在线演示

http://www.homehf.com/teach/20100403/5382.html