简体   繁体   中英

Getting selected option value inside span tag

I need to get the selected option value which resides insides a span tag.

<span id ="resolutionSpan">

    <select name="resolution" id="resolution">
    <option value="0" selected >0</option>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>     
    </select>

</span>

I have tried

var e = document.getElementById("resolution");
console.log( e.options[e.selectedIndex].text);

But that returns a null value. Do i need to iterate the span first?

Due to project limitations, i cant use jquery. Need ur comments in javascript

Get the .options , then .selectedIndex , then .text . Like this:

 var selected = document.getElementById('resolution').options[document.getElementById('resolution').selectedIndex].text alert(selected); 
 <span id ="resolutionSpan"> <select name="resolution" id="resolution"> <option value="0" selected >0</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> </select> </span> 

Hope this helps!

I believe .text selects the label.

If you want the value of the selected item use .value.

fiddle: http://jsfiddle.net/9wxqmLL1/

var e = document.getElementById("resolution");
console.log( e.options[e.selectedIndex].value);

Your code is actually very close, just change .text to .value:

var e = document.getElementById("resolution");
console.log( e.options[e.selectedIndex].value);

unless you wanted to get the actual content of the option (which in this case is the same value but still)

var e = document.getElementById("resolution");
console.log( e.options[e.selectedIndex].innerHTML);

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