Let's say there's a checkbox named CheckBox1 on the Web page with a form,form named Form1.
The code is as follows |
|
var f = document.form1; var sum=0; if (f.checkbox1.length) { for (var i=0;i <f.checkbox1.length;i++) { if (f.checkbox1[i].checked==true) sum=sum+1; } }else{ if (f.checkbox1.checked) { Sum=1; } } Console.log (sum); |
Note that the outermost if judgment, f.checkbox1.length returns undefined when there is only one checkbox item.
Look at one more.
The code is as follows |
|
<script> function test () { var x=document.getelementsbyname ("enjoy[]"); var Issel=false; for (Var i=0;i<x.length;i++) { if (x[i].checked) { Issel=true; return Issel; } } return Issel; } </script> <body> <form id= "Form1" Name= "Form1" method= "Post" action= "" > <input type= "checkbox" Name= "enjoy[]" id= "enjoy["/> Eat <input type= "checkbox" Name= "enjoy[]" id= "enjoy["/> Drink <input type= "Submit" name= "button" id= "button" onclick= "Alert (Test ());" value= "Submit"/> </form> |
Get to the selected checkbox there are several, the next operation will not be more introduced it.