【问题标题】:Bootstrap Select - Set selected value by textBootstrap Select - 通过文本设置选定值
【发布时间】:2016-05-17 16:28:30
【问题描述】:

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

这是我的选择 -

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

【问题讨论】:

  • 所以你想通过下拉列表里面的文字知道,值是什么?您可以在 if 语句中使用 jQuery。
  • 或者你想设置一个选项来选择它的文本?
  • @mikegohome - 是的,我想设置一个选项以通过其文本选择。

标签: twitter-bootstrap-3 bootstrap-select


【解决方案1】:

您可以像下面这样使用 jquery filter() 和 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

【讨论】:

  • 我的选择下拉菜单是使用 Bootstrap Select 插件渲染的,所以上面的经典实现不起作用。
【解决方案2】:

试试这个:

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

【讨论】:

    猜你喜欢
    • 2010-10-04
    • 1970-01-01
    • 2017-12-20
    • 2015-04-04
    • 2017-07-15
    • 1970-01-01
    • 2013-07-01
    • 1970-01-01
    • 2013-02-24
    相关资源
    最近更新 更多