简体   繁体   中英

Selecting options in a select via JQuery

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?

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 comments ).

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 comment 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 complicated 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

试试这个(确保你选择一个ID,我使用mySelect ):

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM