javascript获取checkbox的值

  时间:2017-03-22
本文章向大家介绍js如何获取checkbox的值,需要的朋友可以参考一下。

javascript获取checkbox的值,实例如下:

<html>
    <form name="orderForm">
      <input type="checkbox" name="onion" value="hot onion">Onion<br>
      <input type="checkbox" name="bacon" value="spicy bacon">Bacon<hr>
      <input type="button" value="Order Pizza" name="orderButton" onClick="console.log('ordered.')">
    </form>
    <script language="JavaScript">
    document.write(document.orderForm.onion.value);   
    document.write(" or ",document.orderForm.bacon.value);  
    </script>
</html>

 

再来看一个实例,该实例获取所有被选中的checkbox值:

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

原文地址:http://www.manongjc.com/article/1817.html