By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
437,636 Members | 1,213 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 437,636 IT Pros & Developers. It's quick & easy.

Validating multiple select boxes

P: 4
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
Share this Question
Share on Google+
3 Replies


acoder
Expert Mod 15k+
P: 16,027
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

P: 4
Thanks a lot. Seems obvious now. :-)
Aug 11 '08 #3

acoder
Expert Mod 15k+
P: 16,027
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.