How to get Javascript Select box's selected text
JavascriptSelectJavascript Problem Overview
This things works perfectly
<select name="selectbox" onchange="alert(this.value)">
But I want to select the text. I tried in this way
<select name="selectbox" onchange="alert(this.text)">
It shows undefined. I found how to use DOM to get text. But I want to do this in this way, I means like using just this.value.
Javascript Solutions
Solution 1 - Javascript
this.options[this.selectedIndex].innerHTML
should provide you with the "displayed" text of the selected item. this.value
, like you said, merely provides the value of the value
attribute.
Solution 2 - Javascript
In order to get the value of the selected item you can do the following:
this.options[this.selectedIndex].text
Here the different options
of the select are accessed, and the SelectedIndex
is used to choose the selected one, then its text
is being accessed.
Read more about the select DOM here.
Solution 3 - Javascript
Please try this code:
$("#YourSelect>option:selected").html()
Solution 4 - Javascript
Just use
$('#SelectBoxId option:selected').text();
For Getting text as listed
$('#SelectBoxId').val();
For Getting selected Index value
Solution 5 - Javascript
I know no-one is asking for a jQuery solution here, but might be worth mentioning that with jQuery you can just ask for:$('#selectorid').val()
Solution 6 - Javascript
If you want to get the value, you can use this code for a select element with the id="selectBox"
let myValue = document.querySelector("#selectBox").value;
If you want to get the text, you can use this code
var sel = document.getElementById("selectBox");
var text= sel.options[sel.selectedIndex].text;
Solution 7 - Javascript
The question was not for the value but for the text. Imagine you have something like :
<select name="select">
<option value="1">0.5</option
<option value="2">0.7</option
</select>
And you need to catch the text. So for me I have tried with html (php), and
this.options[this.selectedIndex].text
(from Delan Azabani) doesn't work but
this.options[selectedIndex].text
work, like this on HTML