Results 1 to 3 of 3

Thread: Select object value

  1. #1
    Join Date
    Nov 2009
    Location
    Isfahan, Iran
    Posts
    229
    Thanks
    46
    Thanked 1 Time in 1 Post

    Default Select object value

    Hi,

    I just saw the following:
    http://www.w3schools.com/jsref/prop_option_value.asp

    And wonder if there's something wrong with selectObject.value. Why not a simple approach:

    Code:
    <!DOCTYPE html>
    <html>
    <head>
    <script type="text/javascript">
    function displayResult()
    {
    alert(document.getElementById("mySelect").value);
    }
    </script>
    </head>
    <body>
    
    <form>
    Select your favorite fruit:
    <select id="mySelect">
      <option value="apple">Apple</option>
      <option value="orange">Orange</option>
      <option value="pineapple">Pineapple</option>
      <option value="banana">Banana</option>
    </select>
    </form>
    
    <button type="button" onclick="displayResult()">Display value of selected fruit</button>
    
    </body>
    </html>
    It seems to be working with no problem.

    Thanks in advance!
    Mike

  2. #2
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    30,495
    Thanks
    82
    Thanked 3,449 Times in 3,410 Posts
    Blog Entries
    12

    Default

    In my experience there's nothing wrong with that approach. I believe that in very early browsers - before document.getElementById you may have needed to use the:

    Code:
    selectElement.options[selectElement.options.selectedIndex].value
    And that still works, and sometimes, depending upon the circumstances you might want or even need the selectedIndex for your code. So it's good to know that it exists and how to access it via javascript.

    But again, as far as I know, any browser that does document.getElementById will access the value directly. If that's all you need, that's all you have to do:

    Code:
    selectElement.value

    BTW, that page on w3schools assumes there are no other option elements on the page before the ones you're interested in. If there were, the incorrect value would be returned. But if you do it like I have it (either example above), the correct value will be returned regardless of other option elements on the page.
    Last edited by jscheuer1; 06-09-2012 at 07:00 AM. Reason: detail
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

  3. #3
    Join Date
    Nov 2009
    Location
    Isfahan, Iran
    Posts
    229
    Thanks
    46
    Thanked 1 Time in 1 Post

    Thumbs up

    Dear John,

    Thanks for the confirmation!

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •