Bootstrap Select - 通过文本设置选定值

Bootstrap Select - Set selected value by text

如果我只知道文本而不知道值,如何更改下拉菜单?

这是我的 select -

 <select id="app_id" class="selectpicker">
       <option value="">--Select--</option>
       <option value="1">Application 1</option>
       <option value="2">Application 2</option>
 </select>

你可以像下面这样使用jqueryfilter() and prop()

jQuery("#app_id option").filter(function(){
    return $.trim($(this).text()) ==  'Application 2'
}).prop('selected', true);

DEMO

使用 BOOTSTRAP SELECT,

jQuery("#app_id option").filter(function(){
    return $.trim($(this).text()) ==  'Application 2'
}).prop('selected', true);
$('#app_id').selectpicker('refresh');

DEMO

试试这个:

$(function(){

  // Init selectpicker
  $('#app_id').selectpicker({
    style: 'btn-info',
    size: 4
  });

  // Set desired text 
  var optionToSet = "Application 1";

  $("#app_id option").filter(function(){
    // Get the option by its text
    var hasText = $.trim($(this).text()) ==  optionToSet;
    if(hasText){
    // Set the "selected" value of the <select>.
    $("#app_id").val($(this).val());
    // Force a refresh.
    $("#app_id").selectpicker('refresh')
    }
  });

});

受@Sathish 的回答启发

Working JSfiddle