Aajahid
Aajahid

Reputation: 1686

How to get Javascript Select box's selected text

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

Answers (7)

Eric Dienot
Eric Dienot

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

Michael Albers
Michael Albers

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

Marvil Joy
Marvil Joy

Reputation: 662

Just use

$('#SelectBoxId option:selected').text(); For Getting text as listed

$('#SelectBoxId').val(); For Getting selected Index value

Upvotes: 34

Andre Morata
Andre Morata

Reputation: 641

Please try this code:

$("#YourSelect>option:selected").html()

Upvotes: 37

Michiel
Michiel

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

Oded
Oded

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

Delan Azabani
Delan Azabani

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

Related Questions