user3818036
user3818036

Reputation: 1

How to see if a drop down element is selected

I am new to javascript, and I want to print out a selected item from a drop down menu.

Here is the HTML code:

<fieldset>
    <label>3. Select your operating system</label>&nbsp;
    <select class="form-control" name="Os">
        <option selected="selected" value="select one">- select one -</option>
        <optgroup label="Basic">
            <option value="OSX">Mac OSX</option>
            <option value="windows">Windows</option> 
        </optgroup> 
        <optgroup label="Advanced">
            <option value="linux">Linux</option>
        </optgroup>
    </select>
</fieldset>

My javascript code is:

<script type= text/javascript>
    var e = document.getElementByName("Os");
    var strUser = e.options[e.selectedIndex].value;
    document.writeln(strUser);
</script>

For some reason it won't print the selected value. Any ideas?

Upvotes: 0

Views: 43

Answers (1)

adeneo
adeneo

Reputation: 318182

There is no getElementByName, it's getElementsByName and it gets a nodeList

var strUser = document.getElementsByName("Os")[0].value;

FIDDLE

and make sure the script tag comes after the elements in the DOM

Upvotes: 1

Related Questions