You are here: irt.org | FAQ | JavaScript | Form | 3.2 | Q797 [ previous next ]
The following demonstrates how to cycle through the form elements array picking out select boxes by name (where name includes the work 'select') or by type on browers that support JavaScript 1.1:
<FORM NAME="formName"> <SELECT NAME="select1name"> <OPTION VALUE="">Pick One: <OPTION VALUE="apple">Apple <OPTION VALUE="orange">Orange <OPTION VALUE="banana">Banana </SELECT> <SELECT NAME="select2name"> <OPTION VALUE="">Pick One: <OPTION VALUE="cider">Cider <OPTION VALUE="juice">Juice <OPTION VALUE="milkshake">Milkshake </SELECT> <INPUT TYPE="BUTTON" onClick="cycle()" VALUE="Check"> <BR> <INPUT TYPE="TEXT" NAME="answer"> </FORM> <SCRIPT LANGUAGE="JavaScript"><!-- function cycle() { var answer = ''; for (var i = 0; i<document.formName.elements.length; i++) { if ((document.formName.elements[i].name.indexOf('select') > -1)) { if (document.formName.elements[i].selectedIndex != 0) { answer += document.formName.elements[i].options[document.formName.elements[i].selectedIndex].value + ' '; } } } document.formName.answer.value = answer; } //--></SCRIPT> <SCRIPT LANGUAGE="JavaScript1.1"><!-- function cycle() { var answer = ''; for (var i = 0; i<document.formName.elements.length; i++) { if ((document.formName.elements[i].type == 'select-one')) { if (document.formName.elements[i].selectedIndex != 0) { answer += document.formName.elements[i].options[document.formName.elements[i].selectedIndex].value + ' '; } } } document.formName.answer.value = answer; } //--></SCRIPT>