beckelmw
beckelmw

Reputation: 1236

How do I select an item by its text value in a dropdown using jQuery?

If I had the following select, and did not know the value to use to select an item in advance like in this question or the index of the item I wanted selected, how could I select one of the options with jQuery if I did know the text value like Option C?

<select id='list'>
<option value='45'>Option A</option>
<option value='23'>Option B</option>
<option value='17'>Option C</option>
</select>

Upvotes: 16

Views: 31439

Answers (4)

Pavel Chuchuva
Pavel Chuchuva

Reputation: 22475

$("#list option").each(function() {
  this.selected = $(this).text() == "Option C";
});

Upvotes: 10

RhinoDevX64
RhinoDevX64

Reputation: 707

function SelectItemInDropDownList(itemToFind){    
         var option;
         $('#list option').each(function(){
             if($(this).text() == itemToFind) {
                 option = this;
                 option.selected = true;
                 return false;    
                }
           });  }

I only modified the previous code because it only located the option in the select list, some may want a literal demonstration.

Upvotes: 4

Shog9
Shog9

Reputation: 159688

This should do the trick:

// option text to search for
var optText = "Option B";
// find option value that corresponds
var optVal = $("#list option:contains('"+optText+"')").attr('value');
// select the option value 
$("#list").val( optVal )

As eyelidlessness points out, this will behave unpredictably when the text being searched for can be found in more than one option.

Upvotes: 14

eyelidlessness
eyelidlessness

Reputation: 63529

var option;
$('#list option').each(function() {
    if($(this).text() == 'Option C') {
        option = this;
        return false;
    }
});

Upvotes: 14

Related Questions