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

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Phil Gent
    New Member
    • Mar 2011
    • 13

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

    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;-
    Code:
    <form id='FormID' action='action.php'>
      <select name='select1'>
        <option>Option 1</option>
        <option>Option 2</option>
        <option>Option 3</option>
      </select>
         
      <select name=select2'>
        <option>Option 1</option>
        <option>Option 2</option>
        <option>Option 3</option>
      </select>
        
      <select name='select3'>
        <option>Option 1</option>
        <option>Option 2</option>
        <option>Option 3</option>
      </select>
    </form>
    I had written a piece of code;-
    Code:
       var elem = document.getElementById('FormID').elements;
          for(var i = 0; i < elem.length; i++)
            {
              if (elem[i].value == "")
                {
                  alert("One of the fields was blank");
                  return;
                }
            }
    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
  • Dormilich
    Recognized Expert Expert
    • Aug 2008
    • 8694

    #2
    IE requires the value attribute in the option tag to work like that. i.e.
    Code:
      <select name='select1'>
        <option value="Option 1">Option 1</option>
        <option value="Option 2">Option 2</option>
        <option value="Option 3">Option 3</option>
      </select>

    Comment

    • Phil Gent
      New Member
      • Mar 2011
      • 13

      #3
      Thanks Dormlich for your prompt, concise and helpful response !
      Worked a treat :-)

      Comment

      • Dormilich
        Recognized Expert Expert
        • Aug 2008
        • 8694

        #4
        it’s a known problem, you just have to know the right google keywords to look it up again.

        Comment

        Working...