How to get Javascript Select box's selected text

JavascriptSelect

Javascript 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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAajahidView Question on Stackoverflow
Solution 1 - JavascriptDelan AzabaniView Answer on Stackoverflow
Solution 2 - JavascriptOdedView Answer on Stackoverflow
Solution 3 - JavascriptAndre MorataView Answer on Stackoverflow
Solution 4 - JavascriptMarvil JoyView Answer on Stackoverflow
Solution 5 - JavascriptMichielView Answer on Stackoverflow
Solution 6 - JavascriptMichael AlbersView Answer on Stackoverflow
Solution 7 - JavascriptEric DienotView Answer on Stackoverflow