代码之家  ›  专栏  ›  技术社区  ›  jagamot

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

  •  4
  • jagamot  · 技术社区  · 9 年前

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

    这是我的选择-

     <select id="app_id" class="selectpicker">
           <option value="">--Select--</option>
           <option value="1">Application 1</option>
           <option value="2">Application 2</option>
     </select>
    
    2 回复  |  直到 9 年前
        1
  •  13
  •   Sathish    9 年前

    您可以使用jquery filter() prop() 如下所示

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

    DEMO

    使用 引导选择 ,

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

    DEMO

        2
  •  0
  •   Leo    9 年前

    试试这个:

    $(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