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.
This question is related to
javascript
select
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.
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.
Just use
$('#SelectBoxId option:selected').text();
For Getting text as listed
$('#SelectBoxId').val();
For Getting selected Index value
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;
Please try this code:
$("#YourSelect>option:selected").html()
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()
Source: Stackoverflow.com