469,354 Members | 2,406 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,354 developers. It's quick & easy.

Validating multiple select boxes

Hi,

I'm currently trying to write a loop that can be used on several select boxes within the same form.

Some sample HTML:
[HTML]<!-- select box 1 -->
<select name="qtyItsallgreek" id="qtyItsallgreek">
<option value="0" selected="selected">0</option><option value="1">1</option>
<option value="2">2</option><option value="3">3</option>
</select>
<!-- select box 2 -->
<select name="qtyBlueberrynights" id="qtyBlueberrynights">
<option value="0" selected="selected">0</option><option value="1">1</option>
<option value="2">2</option><option value="3">3</option>
</select>[/HTML]

All form validation is done once the user hits a button that calls my main() function, which in turn calls a check_input function:

Expand|Select|Wrap|Line Numbers
  1. function check_input(element) {
  2.     if (element.match(/^qty.*$/)) {
  3.      var x = document.getElementById('orderform').qtyItsallgreek.selectedIndex;
  4.      var y = document.getElementById.element.selectedIndex;
  5.      return true;
  6.     }
  7. }
  8. function main() {
  9.     var myForm = document.getElementById('orderform');
  10.         for (var i = 0; i < myForm.elements.length; i += 1) {
  11.             var e = myForm.elements[i];
  12.             if (e.type === "select-one") {
  13.                 check_input(e.id);
  14.             }
  15. }
  16.  
While var x contains the selectedIndex value, var y is interpreted literally, which gives the error that document.getElementById.element.selectedIndex is undefined.

Instead of referring to each specific select box like var x, is it possible to use the element variable in a similar way to var y?

You might have noticed I'm quite new to JavaScript :-)

PS. In the second code block on line 3, there shouldn't be a space within the word 'greek' - It's a non-breaking space that I can't get the message editor to remove :-)
Aug 10 '08 #1
3 1465
acoder
16,027 Expert Mod 8TB
Since you're passing the ID, just pass the value to the getElementById method:
Expand|Select|Wrap|Line Numbers
  1. var y = document.getElementById(element).selectedIndex;
  2.  
Aug 11 '08 #2
Thanks a lot. Seems obvious now. :-)
Aug 11 '08 #3
acoder
16,027 Expert Mod 8TB
You're welcome. Post again back to the forum if you have more questions :)
Aug 12 '08 #4

Post your reply

Sign in to post your reply or Sign up for a free account.

By using this site, you agree to our Privacy Policy and Terms of Use.