Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - How to select dropdown list item by text?

Tags:

How would I select my dropdown list item by text rather than value?

I want to select a dropdown item by text with jQuery.

like image 917
nunu Avatar asked Jan 21 '11 09:01

nunu


People also ask

How do I select a specific value in a DropDownList using jQuery?

Projects In JavaScript & JQuery With jQuery, it's easy to get selected text from a drop-down list. This is done using the select id. To change the selected value of a drop-down list, use the val() method.

How do I get selected text option in select?

To get the text of the selected option, we first need to find the selected option using the find() method and then use the text() method to get the option text. where selectBox is the value of the id attribute of the <select> HTML tag.

Which of the following is the correct way to select an option based on its text in jQuery?

Select from option value is pretty easy and it is as below: $('select option[value="test"]'). val(); So now selecting by text, If you are using jQuery and if you have an older version than 1.9 the following will work choosing by text.


2 Answers

use :contains()(link)

$("select option:contains(text)").attr('selected', true); 

demo

like image 173
Reigel Avatar answered Jan 22 '23 05:01

Reigel


There is a filter function on jQuery that you can use to get elements with something more specific

$("select option").filter(function() {     return $(this).text() == "text_to_select"; }); 

This is going to return all options with the "text_to_select" in the text.

like image 24
BrunoLM Avatar answered Jan 22 '23 04:01

BrunoLM