Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 291
Aajahid Avatar asked Jul 03 '10 07:07

Aajahid


People also ask

How do I get the text value of a selected option in JavaScript?

function myNewFunction(element) { var text = element. options[element. selectedIndex]. text; // ... }

How do I get selected value in select?

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).

How do you get selected option text in react JS?

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.


3 Answers

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.

like image 172
Delan Azabani Avatar answered Oct 13 '22 06:10

Delan Azabani


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.

like image 30
Oded Avatar answered Oct 13 '22 04:10

Oded


Please try this code:

$("#YourSelect>option:selected").html()
like image 37
Andre Morata Avatar answered Oct 13 '22 05:10

Andre Morata