Thursday, September 8, 2016

JAVASCRIPT: Accessing selected value inside SELECT(dropdown) element

This is what a SELECT element looks like:


<select id= "tsoID">
  <!-- Volvo is here selected -->
  <option value="volvo" selected="selected">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>


It can get pretty tricky to programmatically find the 'value' of the chosen option inside <select> tag.

However, the work becomes simpler in this way:


var e1 = document.getElementById("tsoID");
var e1Value = e1.options[e1.selectedIndex].value;

Basically, find the element by ID and then get the value of the selected option by accessing at index = e1.selectedIndex

This will return 'volvo' inside e1Value.

No comments:

Post a Comment