2016-02-08 40 views
2

如果我只知道文本而不是值,我該如何更改下拉菜單?引導選擇 - 通過文本設置所選值

這是我的選擇 -

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

所以你想通過下拉菜單裏面的文字知道,這個值是什麼?你可以在if語句中使用jQuery。 –

+1

http://stackoverflow.com/questions/14804253/how-to-set-selected-value-on-select-using-selectpicker-plugin-from-bootstrap –

+0

或者你想設置一個選項來選擇它的文本? – Leo

回答

6

您可以使用jQuery filter()prop()像下面

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

DEMO

使用自舉SELECT

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

DEMO

+0

我的選擇下拉是使用Bootstrap Select插件呈現的,因此上述經典實現將不起作用。 – jagamot

+0

我已經更新了我的答案 – Sathish

0

試試這個:

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

相關問題