Reputation: 405
I am attempting to select the text that is shown in my select menu. On change I would like to know what text was select and not the value.
I am able to do this for the value with this.value
but when attempting to do this.label
or this.text
I am getting an undefined return.
How can I get the text shown in the drop down menu and not the value?
If I do this.title
then its showing the title of my select menu not the actual the title of the option
Here is an example of my code:
$("#test").change(function() {
let selectValue = this.value
console.log(selectValue)
let title = this.title
console.log((this.options[this.selectedIndex]))
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="test" title="test">
<option value="high school">Academic</option>
<option value="online">Retail</option>
</select>
I am expecting to see a return value "Academic" and not "high school" or "Retail" and not "online"
Upvotes: 0
Views: 40
Reputation: 3968
Get the selected option by this.options
and this.selectedIndex
console.log(this.options[this.selectedIndex])
$("#test").change(function() {
let selectedOption = this.options[this.selectedIndex];
console.log(selectedOption.innerHTML);
console.log($(selectedOption).text());
console.log($(selectedOption).html());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="test" title="test">
<option value="high school">Academic</option>
<option value="online">Retail</option>
</select>
Upvotes: 1