Search code examples
jquerytwitter-bootstrapbootstrap-select

Search text in Bootstrap's SelectPicker using jQuery


I want to search text in dropdown and set it selected by text.Here is my control

HTML:

  <select class="form-control input-sm selectpicker" id="area_location_id">
        <option value="" selected="">Select</option>
        <option value="17">Al Barsha</option>
       <option value="82">Al Furjan</option>
      <option value="4924">Al Garhoud</option>
      <option value="5787">Al Jadaf</option>
     <option value="5684">Al Mamzar</option
    </select>

Jquery:

 var mytxt = "Al Furjan";
("#area_location_id").find("option:contains('" + mytxt  + "')").each(function () {
    $(this).attr("selected", "selected");
});
$('#area_location_id').selectpicker('refresh');
$('#area_location_id').selectpicker('val', mytxt );

I am using bootstrap selectpicker. Can I use contain: in this code or does selectpicker have its own method?

UPDATED:

I tried with simple select control and it is working...Here is Fiddle


Solution

  • For those who need solution for the same situation,I resolved it like here

    var userToSearchFor = "Jadaf";
    $("#area_location_id").find("option:contains('" + userToSearchFor +"')")
    .each(function ()   {
     $(this).attr("selected", "selected");
    });
    
    $('#area_location_id').selectpicker('val', userToSearchFor );
    $('#area_location_id').selectpicker('refresh');