4

How can I change the drop down if I only know the text and not the value?

Here is my select -

 <select id="app_id" class="selectpicker">
       <option value="">--Select--</option>
       <option value="1">Application 1</option>
       <option value="2">Application 2</option>
 </select>
jagamot
  • 5,348
  • 18
  • 59
  • 96

2 Answers2

13

You can use jquery filter() and prop() like below

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

DEMO

Using BOOTSTRAP SELECT,

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

DEMO

Sathish
  • 2,440
  • 1
  • 11
  • 27
  • 1
    My select drop down is rendered using Bootstrap Select plugin, so the above classic implementation won't work. – jagamot Feb 08 '16 at 04:50
0

Try this:

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

});

Inspired by @Sathish's answer

Working JSfiddle

Leo
  • 1,051
  • 2
  • 13
  • 33