admin管理员组

文章数量:1318580

I have a select with the following options:

<select>
     <option value="1">A</option>
     <option value="2">B</option>
     <option value="3">C</option>
</select>

I don't know what the values are, but in my JQuery code, I want to select option two because I know that the text is B (but nothing else).

How can it be done?

I have a select with the following options:

<select>
     <option value="1">A</option>
     <option value="2">B</option>
     <option value="3">C</option>
</select>

I don't know what the values are, but in my JQuery code, I want to select option two because I know that the text is B (but nothing else).

How can it be done?

Share Improve this question edited Dec 12, 2014 at 22:29 rtruszk 3,92213 gold badges39 silver badges53 bronze badges asked May 23, 2012 at 7:38 cdubcdub 25.8k60 gold badges186 silver badges329 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 4

You can use the :contains() selector:

$('option:contains("B")').prop('selected', true);

Alternatively:

$('option')
    .filter(function() {
        return this.text == 'B'; 
    })
    .prop('selected', true);

If you're not sure what the values are, but know what the text inside is, you can use the :contains() selector to get the appropriate option, get its value, then set the select.

Note that :contains() performs a substring match, so :contains(foo) will select both <p>foo</p> and <p>barfoobar</p> (as ThiefMaster points out in the ments).

For more granular control on selection, you'll want the .filter() option I've mentioned farther down.

// relevant option
//     : not entirely sure if .val() will get an option's value
var _optionval = $('option:contains("B")').attr('value');

// set select value
$('select').val(_optionval);

EDIT

I'm sharing the following based off of your ment on Jack's answer.

:contains() is basically designed to perform a matching against an element's contents. No going around that.

You can, however, use something like .filter() to write more plicated code.

$('option').filter(function () {

    // we want the option (or optionS) with text that starts with "foo"
    return $(this).text().indexOf('foo') === 0;

    // or maybe just something with an exact match
    //
    // return $(this).text() === 'foo';
});
<select id="select_id">
 <option value="1">A</option>
 <option value="2">B</option>
 <option value="3">C</option>
</select>

$("#select_id option").each(function (){
   if($(this).text()=='B'){
       // DO what you want to  
   }
});

this code will select your any option in select field with text "B". i think this is what you want

Try this (make sure you give your select an ID, i've used mySelect):

$("#mySelect").val($("#mySelect:option:contains('B')").val());
$('option').each(function(){
    var t=this
    if(t.text=='B'){
       t.selected='selected';
    }
});​

本文标签: javascriptSelecting options in a select via JQueryStack Overflow