Mori
Mori

Reputation: 6780

Select object value

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

Upvotes: 1

Views: 10928

Answers (1)

John Stimac
John Stimac

Reputation: 5493

Your method, document.getElementById("mySelect").value is returning the value of the select object - which sets itsself to the value of the currently selected option. The way w3Schools is doing it is finding the actual option tag, then you're getting the value of the option tag. So, as long as you are accessing the currently selected option tag, they return the exact same thing. However, the w3schools way allows you to actually set the value of the option tag instead of changing which option is selected when setting the value property (although that's probably not what you want).

Example:

​<select id='select'>
    <option value=1>one</option>
    <option value=2>two</option>
​</select>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
x=document.getElementById("mySelect").selectedIndex;

So, document.getElementById('select').value; returns the value of the select element.

And document.getElementsByTagName("option")[x].value​; returns the value of the selected option element.

Meaning that document.getElementById('select').value​=2​​​​ changes which option is selected, while document.getElementsByTagName("option")[x].value​=2 changes the value of the selected option element.

TLDR: When getting the value there is no difference, when setting the value there is.

Upvotes: 5

Related Questions