Mike Marks
Mike Marks

Reputation: 10139

Setting Drop Down List's selected value based on the option value's text rather than value using jQuery

I want to be able to set the "selected" item in my drop down list to be the option value whose text equals "None". Here's my drop down list:

<select data-val="true" data-val-number="The field SecondaryFillerFk must be a number." data-val-required="The SecondaryFillerFk field is required." id="SecondaryFillerFk" name="SecondaryFillerFk">
    <option value="46">Lactose, Spray-Dried</option>
    <option value="47">Microcrystalline Celluose</option>
    <option value="48">Sodium Bicarbonate</option>
    <option value="49">Methocel E4M</option>
    <option value="50">Methocel K100M</option>
    <option value="53">None</option>
</select>

The following jQuery obviously does not work, because it's looking for the value of "None", which doesn't exist.

$('#SecondaryFillerFk').val('None');

QUESTION: How can I set the selected value of my drop down list to be the option item whose TEXT is equal to "None"?

Upvotes: 1

Views: 5648

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388316

Try

$('#SecondaryFillerFk option:contains("None")').prop('selected', true);

Demo: Fiddle

Note: This may fail if there is another option with text Nonexxxx, then you need

$('#SecondaryFillerFk option').filter(function(){
    return $.trim($(this).text()) == 'None'
}).prop('selected', true);

Demo: Fiddle

Upvotes: 3

Related Questions