下面的JS代码可以统计表单中有多少个checkbox被选中,在问卷调查中经常会用到
<form name="form3" action="#"> <div>Who are your favorite browncoats? Please select all that apply to you: <input type="checkbox" name="Zoe" />Zoe <input type="checkbox" name="Mal" />Mal <input type="checkbox" name="Inara" />Inara <input type="checkbox" name="Kaylee" /> Kaylee <input type="checkbox" name="River" />River <input type="checkbox" name="Simon" /> Simon </div> <input type="submit" name="NEXT" value="GO! " /> </form> <script type="text/javascript" ><!-- //returns how many checkboxes in the form are checked function howManyChecks(form) { var selections = 0; for (var i=0; i<form.length; i++) { var theElement = form.elements[i]; if(theElement.type == "checkbox") { if(theElement.checked == true) { selections++ } } } return selections } function validate() { var num = howManyChecks(document.forms["form3"]) if( num == 0) { alert("Please make a selection."); } else { alert("Number of favorite characters: "+num) } return false; } document.forms["form3"].elements["NEXT"].onclick=validate; //--> </script>