Search code examples
phpjqueryajaxbootstrap-selectpicker

Dynamically Set Value in seletpiker using jquery and Ajax


I am getting City List From Database and I Want to Show the Selected City Selected While Edit Operation.

I am Using Ajax for Getting a value from Database. That's Work Nicely. I get the Response Data From My Controller. Now The Problem is I am not Able to set a value on selectpiker. I get City Name In Ajax Response.

I have tried Some Example but did not work.

Here is the Ajax Code.

    $.ajax({  
     type: "GET",
     url: urlForGetCityList,             
     dataType: 'Json',                
     success: function(response){ 
         console.log(response.cityName);

          // This is What i Tried For getting SeletBox Selected.
         var $select = $('#city');
         $select.val(response.city).trigger('change');

         // I have also Tried Some Selct2 Option for it. But it didn't work.
         $("#city").select2("val", response.city);

        // And at Last I have tried for like simple select box.
        $("#city").val(response.city);

    });

None of this work properly. Here is the HTML Code of Selectpiker.

<div class="col-md-4">
<div class="form-group">
    <label for="field-3" class="control-label">City *</label> 
    <select class="selectpicker" data-live-search="true" data-style="btn-white" name="city" id="city"
        title="Select City">
        <option value="city1">City 1</option>
        <option value="city2">City 2</option>
    </select>
</div>
</div>

Solution

  • You Already Reach to the half you're a problem is just this select piker is not showing the selected value because it's that way you should check this. So Try This.

    $('select[name=city]').val(response.city);
    $('.selectpicker').selectpicker('refresh');