Selecting options in a select via JQuery

若如初见. 提交于 2019-12-23 17:13:42

问题


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?


回答1:


You can use the :contains() selector:

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

Alternatively:

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



回答2:


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';
});



回答3:


<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




回答4:


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

$("#mySelect").val($("#mySelect:option:contains('B')").val());



回答5:


$('option').each(function(){
    var t=this
    if(t.text=='B'){
       t.selected='selected';
    }
});​


来源:https://stackoverflow.com/questions/10715466/selecting-options-in-a-select-via-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!