jQuery set dropdown option based on text

mrgstiffler

[H]F Junkie
Joined
Dec 20, 2000
Messages
13,408
I've looked up a few examples on how to do this, but none of them seem to work anymore.

I want to be able to set the selected attribute on a dropdown menu based on the option text NOT value.

Code:
<select id="dropDownMenu">
  <option value="0">First Option</option>
  <option value="1">Second Option</option>
  <option value="2">Third Option</option>
</select>

I want to be able to set the option with "Second Option" text as selected. Everything I've tried has failed failed failed.
 
Code:
$('#dropDownMenu').val(1);
Is that what you mean?

I need to do it based off the text and not the value.

And your example wont change the selected dropdown option. It will just set the value.

Code:
$('#caseAgencyDropDown option:eq(0)').attr("selected", "selected");

Is what would actually select it.
 
How about this

Code:
$('#dropDownMenu option:first').attr('selected', 'selected');

Or this:

Code:
function selectAccordingToText(optionText) {
  $('#dropDownMenu option:contains("' + optionText + '")').attr('selected', 'selected');
}
 
/sigh...

It's VERY important to make sure that you're looking at the correct element when testing. option:contains is the first thing I tried but it didn't work. After 30 minutes of trying different things I couldn't get it to work. So I tried using Firebug console to debug it and nothing. Turns out I was looking at the wrong dropdown this whole time.

Oops... and thanks.
 
Back
Top