简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM