Misha Moroshko
Misha Moroshko

Reputation: 171449

jQuery: How to select an option in select box based on option's HTML text?

To get the text of the selected option I do:

$("select option:selected").text()

How could I set an option based on it's text ?

See here

Upvotes: 1

Views: 342

Answers (2)

McHerbie
McHerbie

Reputation: 2995

This would work:

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

Example: http://jsfiddle.net/ADp6L/1/

Upvotes: 3

chprpipr
chprpipr

Reputation: 2039

Clear the old selection out first and then loop through the options, canceling the loop once the correction option is found.

$("select option").removeAttr("selected").each(function() {
    var jThis = $(this);

    if (jThis.text() == "mytext") {
        jThis.attr("selected", "selected");
        return false;
    }

});

Upvotes: 4

Related Questions