PDA

View Full Version : Select object value



Rain Lover
06-09-2012, 03:15 AM
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:


<!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

jscheuer1
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:


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:


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.

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

Thanks for the confirmation! :)