2

I would like to select an option in a drop down menu by its' text. When I run the code,:

var theText = "Large"; $("#size option:contains(" + theText + ")").attr('selected', 'selected');

it selects XLarge instead of Large. Is there any way to make it select Large? JSFiddle: http://jsfiddle.net/r8wuP/2/

user3376905
  • 177
  • 1
  • 3
  • 11
  • possible duplicate of [JQuery :contains function limit to exact match](http://stackoverflow.com/questions/5501228/jquery-contains-function-limit-to-exact-match) and [make jQuery's `:contains()` select only exact string](http://stackoverflow.com/questions/15364298/make-jquerys-contains-select-only-exact-string) – Ram Mar 08 '14 at 16:48
  • `$("#size option").prop('selected', function() { return $(this).text() === theText; });` – adeneo Mar 08 '14 at 17:01

3 Answers3

4

You can use .filter() to find an exact match, :contains-selector returns partial matches also

var theText = "Large";
$("#size option").filter(function () {
    return $.trim($(this).text()) == theText;
}).attr('selected', 'selected');

Demo: Fiddle

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
0

Try this:

http://jsfiddle.net/r8wuP/3/

$('#size').find('option').filter(function() {
    return $(this).text() === 'Large';
}).first().attr('selected', 'selected');
Gavin
  • 7,544
  • 4
  • 52
  • 72
0

Since you're using 1.4 this would work:

var theText = "Large";
$("#size").find("option[text='" + theText + "']").attr('selected', 'selected');

However later jQuery versions might need the filter method.

user2728841
  • 1,333
  • 17
  • 32