javascript如何获取checkbox复选框选中项的值

时间:2017-03-21
本文章向大家介绍javascript如何获取checkbox选中项的值,主要思路是获取所有的checkbox,然后遍历哪些checkbox被选中,最后使用checkbox的value属性获取选中checkbox的值,需要的朋友可以参考一下。

实例一:

<script>
function checkbox()
{
var str=document.getElementsByName("box");
var objarray=str.length;
var chestr="";
for (i=0;i<objarray;i++)
{
  if(str[i].checked == true)
  {
   chestr+=str[i].value+",";
  }
}
if(chestr == "")
{
  alert("请先选择一个爱好~!");
}
else
{
  alert("您先择的是:"+chestr);
}
}
</script>
选择您的爱好:
  <input type="checkbox" name="box" id="box1" value="跳水" />跳水
  <input type="checkbox" name="box" id="box2" value="跑步" />跑步
  <input type="checkbox" name="box" id="box3" value="听音乐" />听音乐
  <input type="button" name="button" id="button" onclick="checkbox()" value="提交" />

在线运行

分析:

  1. 使用document.getElementsByName("box");获取HTML文档中所有的checkbox,获取的结果为数组
  2. 遍历数组,数组中的每个元素为一个checkbox复选框,通过判断checkbox的checked属性来判断checkbox是否被选中,如果checked属性为true,表示选中,此时我们可以使用checkbox的value属性来获取checkbox选中项的值。

再看一个实例:

<input type="checkbox" name="test" value="1"/><span>1</span>
<input type="checkbox" name="test" value="2"/><span>2</span>
<input type="checkbox" name="test" value="3"/><span>3</span>
<input type="checkbox" name="test" value="4"/><span>4</span>
<input type="checkbox" name="test" value="5"/><span>5</span>
<input type='button' value='提交' onclick="fun()"/>
<script>
function fun(){
    obj = document.getElementsByName("test");
    check_val = [];
    for(k in obj){
        if(obj[k].checked)
            check_val.push(obj[k].value);
    }
    alert(check_val);
}
</script>

实现原理和实例一是一样的。

js获取checkbox中所有选中值及input后面所跟的文本.

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>js</title>
</head>
<script language="javascript">
function aa(){
    var r=document.getElementsByName("r");  
    for(var i=0;i<r.length;i++){
         if(r[i].checked){
         alert(r[i].value+","+r[i].nextSibling.nodeValue);
       }
    }      
}
</script>
<body>
<form name="form1" method="post" action="">
<input type="checkbox" name="r" value="1">a<br>
<input type="checkbox" name="r" value="2">b<br>
<input type="checkbox" name="r" value="3">c<br>
<input type="checkbox" name="r" value="4">d<br>
<input type="checkbox" name="r" value="5">e<br>
<input type="checkbox" name="r" value="6">f<br>
<input type="checkbox" name="r" value="7">g<br>
<input type="checkbox" name="r" value="8">h<br>
<input type="checkbox" name="r" value="9">i<br>
<input type="checkbox" name="r" value="10">j<br>
<br>
<input type="button" onclick="aa()" value="button">
</form>
</body>
</html>

注意:使用obj.extSibling.nodeValue获取checkbox选中项的文本。