View Full Version : Select object value

Rain Lover
06-09-2012, 03:15 AM

I just saw the following:

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

<!DOCTYPE html>
<script type="text/javascript">
function displayResult()

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>

<button type="button" onclick="displayResult()">Display value of selected fruit</button>


It seems to be working with no problem.

Thanks in advance!

06-09-2012, 06:52 AM
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:


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:


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.

Rain Lover
06-09-2012, 06:01 PM
Dear John,

Thanks for the confirmation! :)