-1

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

Satheesh
  • 646
  • 1
  • 10
  • 33
  • possible duplicate of [Get selected value of dropdownlist using JavaScript?](http://stackoverflow.com/questions/1085801/get-selected-value-of-dropdownlist-using-javascript) – emerson.marini Nov 19 '14 at 15:55
  • @MelanciaUK Please check that i have mentioned about span tag, consider it before downvoting. – Satheesh Nov 19 '14 at 15:57
  • Duplicate of http://stackoverflow.com/questions/1085801/get-selected-value-of-dropdownlist-using-javascript – Hywel Rees Nov 19 '14 at 15:57
  • Voting is anonymous. – emerson.marini Nov 19 '14 at 15:58
  • @Satheesh the span tag is irrelevant, you are selecting the select by ID. – Dai Nov 19 '14 at 15:58
  • And to get the selected value of a dropdownlist, it doesn't really matter what kind of element is wrapping it. You go for it. Check the duplicated question. – emerson.marini Nov 19 '14 at 15:58
  • The issue was the same span tagname was used by other spans too. I renamed it and everything works fine now. Thanks everyone for the answers. In my scenario, i should go with value not with text. – Satheesh Nov 25 '14 at 09:35

3 Answers3

1

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!

Ian Hazzard
  • 7,661
  • 7
  • 34
  • 60
1

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);
Dai
  • 1,510
  • 1
  • 11
  • 12
1

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);
Serates
  • 106
  • 4