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

How do you retrieve a <select> selected option in javascript ?

P: 13
Hi,

I need to check a form (consisting mostly of select elements) and ensure that none of the values are empty/null.

Unfortunately I don't know how many select elements there will be so I need to be able to loop through as many items as there could possibly be.

Form example;-
Expand|Select|Wrap|Line Numbers
  1. <form id='FormID' action='action.php'>
  2.   <select name='select1'>
  3.     <option>Option 1</option>
  4.     <option>Option 2</option>
  5.     <option>Option 3</option>
  6.   </select>
  7.  
  8.   <select name=select2'>
  9.     <option>Option 1</option>
  10.     <option>Option 2</option>
  11.     <option>Option 3</option>
  12.   </select>
  13.  
  14.   <select name='select3'>
  15.     <option>Option 1</option>
  16.     <option>Option 2</option>
  17.     <option>Option 3</option>
  18.   </select>
  19. </form>
  20.  
I had written a piece of code;-
Expand|Select|Wrap|Line Numbers
  1.    var elem = document.getElementById('FormID').elements;
  2.       for(var i = 0; i < elem.length; i++)
  3.         {
  4.           if (elem[i].value == "")
  5.             {
  6.               alert("One of the fields was blank");
  7.               return;
  8.             }
  9.         }
  10.  
This works fine in firefox, but the select values are always blank in IE8 (the browser that will be using this site mostly).

Can anyone please help me adjust the code above to properly check the fields in IE ?

Many thanks
Phil
Sep 29 '11 #1
Share this Question
Share on Google+
3 Replies


Dormilich
Expert Mod 5K+
P: 8,639
IE requires the value attribute in the option tag to work like that. i.e.
Expand|Select|Wrap|Line Numbers
  1.   <select name='select1'>
  2.     <option value="Option 1">Option 1</option>
  3.     <option value="Option 2">Option 2</option>
  4.     <option value="Option 3">Option 3</option>
  5.   </select>
Sep 29 '11 #2

P: 13
Thanks Dormlich for your prompt, concise and helpful response !
Worked a treat :-)
Sep 29 '11 #3

Dormilich
Expert Mod 5K+
P: 8,639
it’s a known problem, you just have to know the right google keywords to look it up again.
Sep 29 '11 #4

Post your reply

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