Skip to content
Advertisement

Get selected value in dropdown list using JavaScript

How do I get the selected value from a dropdown list using JavaScript?

<form>
  <select id="ddlViewBy">
    <option value="1">test1</option>
    <option value="2" selected="selected">test2</option>
    <option value="3">test3</option>
  </select>
</form>

Advertisement

Answer

Given a select element that looks like this:

<select id="ddlViewBy">
  <option value="1">test1</option>
  <option value="2" selected="selected">test2</option>
  <option value="3">test3</option>
</select>

Running this code:

var e = document.getElementById("ddlViewBy");
var value = e.value;
var text = e.options[e.selectedIndex].text;

Results in:

value == 2
text == "test2"

Interactive example:

var e = document.getElementById("ddlViewBy");
function onChange() {
  var value = e.value;
  var text = e.options[e.selectedIndex].text;
  console.log(value, text);
}
e.onchange = onChange;
onChange();
<form>
  <select id="ddlViewBy">
    <option value="1">test1</option>
    <option value="2" selected="selected">test2</option>
    <option value="3">test3</option>
  </select>
</form>
Advertisement