Page 1 of 1

JavaScript - Get the text of the Selected Option

Posted: 04 May 2015, 10:38
by PloMar
I have a dropdown select list like this:

Code: Select all

<select name="sel1" id="sel1">
  <option value="1">text 1</option>
  <option value="2">txt 2</option>
  <option value="3">text 3</option>
</select>
I can get the value with something like in JS:

Code: Select all

document.getElementById('sel1').addEventListener('change', function(e){
  alert(this.value);
});
But how can I get the actual option text using JavaScript?

JavaScript - Get the text of the Selected Option

Posted: 04 May 2015, 10:40
by MarPlo
Hi,
You can use the selectedIndex property to get the ordered index of the selected option, then, with that index you can get the object with the selected option.
Example:

Code: Select all

Alerts the text of the selected option.
<select name="sites" id="sites">
  <option value="1">MarPlo.net</option>
  <option value="2">CoursesWeb.net</option>
  <option value="3">PHP.net</option>
</select>

<script>
document.getElementById('sites').addEventListener('change', function(e){
  var optxt = e.target.options[e.target.selectedIndex].text;
  alert(optxt);
});
</script>
Demo:
Alerts the text of the selected option.