Reputation: 1686
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.
Upvotes: 83
Views: 239516
Reputation: 1
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
<select ... onChange="upTVA(this.options[selectedIndex].text);">
It is still surprising that for a select this.text
does not work while this.value
works
Upvotes: 0
Reputation: 11
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;
Upvotes: 1
Reputation: 662
Just use
$('#SelectBoxId option:selected').text();
For Getting text as listed
$('#SelectBoxId').val();
For Getting selected Index value
Upvotes: 34
Reputation: 641
Please try this code:
$("#YourSelect>option:selected").html()
Upvotes: 37
Reputation: 4260
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()
Upvotes: 1
Reputation: 499392
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.
Upvotes: 70
Reputation: 81492
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.
Upvotes: 131