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?

0

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I don't want to change the text of the option.. I just need to select the value by TEXT not by INDEX
contains will try to match it's value as well, so you have to use text attribute, $('#cars').find('option[text*="Another Car"]').val();
The first method worked fine. The second one did not. Thanks anyways
0

try this one

var text="text";
var check=$('#cars').find('option[text='+text'+]').val();
        $('#cars').val(check);

1 Comment

this would not work, because the values contain spaces and that would cause errors selecting the right option

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.