JavaScript - Get the text of the Selected Option

Topics related to client-side programming language.
Post questions and answers about JavaScript, Ajax, or jQuery codes and scripts.
PloMar
Posts: 48

JavaScript - Get the text of the Selected Option

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?

MarPlo Posts: 186
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.

Similar Topics