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.
function myNewFunction(element) { var text = element. options[element. selectedIndex]. text; // ... }
To get the value of a select or dropdown in HTML using pure JavaScript, first we get the select tag, in this case by id, and then we get the selected value through the selectedIndex property. The value "en" will be printed on the console (Ctrl + Shift + J to open the console).
The text of an option is simply the label property of the corresponding item . In your case, to retrieve the text of the selected option, you can do: var selectedItem = this.
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.
Please try this code:
$("#YourSelect>option:selected").html()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With