You are here: irt.org | FAQ | JavaScript | Form | 10.2 | Q798 [ previous next ]
Cycling identically named checkboxes require the use of the forms elements array:
<FORM> <INPUT TYPE="CHECKBOX" NAME="myName" VALUE="one"> <INPUT TYPE="CHECKBOX" NAME="myName" VALUE="two"> <INPUT TYPE="CHECKBOX" NAME="myName" VALUE="three"> <INPUT TYPE="CHECKBOX" NAME="myName" VALUE="four"> <INPUT TYPE="CHECKBOX" NAME="myName" VALUE="five"> <INPUT TYPE="CHECKBOX" NAME="myName" VALUE="six"> <INPUT TYPE="BUTTON" onClick="cycleCheckboxes(this.form)" VALUE="Check"> <BR> <INPUT TYPE="TEXT" NAME="answer"> </FORM> <SCRIPT LANGUAGE="JavaScript"><!-- function cycleCheckboxes(what) { for (var i = 0; i<what.elements.length; i++) { if ((what.elements[i].name.indexOf('myName') > -1)) { if (what.elements[i].checked) { what.answer.value = what.elements[i].value; } } } } //--></SCRIPT>
However, the radio button is a more suitable form element to use, as only one of the identically named radio buttons can ever be selected at once. In the previous example, if more than one checkbox had been checked then only the last one would be picked up.
<FORM> <INPUT TYPE="RADIO" NAME="myName" VALUE="one"> <INPUT TYPE="RADIO" NAME="myName" VALUE="two"> <INPUT TYPE="RADIO" NAME="myName" VALUE="three"> <INPUT TYPE="RADIO" NAME="myName" VALUE="four"> <INPUT TYPE="RADIO" NAME="myName" VALUE="five"> <INPUT TYPE="RADIO" NAME="myName" VALUE="six"> <INPUT TYPE="BUTTON" onClick="cycleRadii(this.form)" VALUE="Check"> <BR> <INPUT TYPE="TEXT" NAME="answer"> </FORM> <SCRIPT LANGUAGE="JavaScript"><!-- function cycleRadii(what) { for (var i = 0; i<what.elements.length; i++) { if ((what.elements[i].name.indexOf('myName') > -1)) { if (what.elements[i].checked) { what.answer.value = what.elements[i].value; } } } } //--></SCRIPT>