0

I have the following HTML

<SELECT id='cars'>
   <OPTION value='1'>Car One</option>
   <OPTION value='2'>Second Car</option>
   <OPTION value='3'>Another Car</option>
</SELECT>

And I know that I can change the selected value of the drop-down control to any value using:

$('#cars').val(2);   // This will make the combo text: Second Car

But how can I select a value using the text rather than the value?

What I need to do is something like:

$('#cars').val('Another Car');

or

$('#cars').text('Another Car');

but that has no effect...

Any help?

Ahmad
  • 12,336
  • 6
  • 48
  • 88

2 Answers2

5

If you want to get the value that contains the text, then you may use contains:

$('#cars option:contains("Another Car")');

As per @Burimi suggestion: contains will try to match it's value as well, so you have to use text attribute

$('#cars').find('option[text*="Another Car"]').val();

Sorry, for confusion made by comment. But contains just match it's text not it's value.

Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231
0

try this one

var text="text";
var check=$('#cars').find('option[text='+text'+]').val();
        $('#cars').val(check);
john
  • 567
  • 8
  • 23
  • this would not work, because the values contain spaces and that would cause errors selecting the right option – Ahmad Feb 16 '15 at 12:15