实例一:

< >
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);
}
}
</ >
选择您的爱好:
  <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\"  =\"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=\'提交\'  =\"fun()\"/>
< >
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);
}
</ >

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

 

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

<html>
<head>
<  http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">
< >js</ >
</head>
<  language=\" \">
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);
       }
    }      
}
</ >
<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\"  =\"aa()\" value=\"button\">
</form>
</body>
</html>

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

收藏 打印