动态填充搜索框(select)bootstrap jquery中的选项

时间:2016-11-04 22:43:01

标签: javascript php jquery html twitter-bootstrap

我正在关注这个(http://www.jquery-az.com/boots/demo.php?ex=6.0_6)搜索框,但我的情况有点不同。我有动态填充的国家,城市和位置,我希望我的搜索框主要在位置上。
当位置动态填充时,选项不会在搜索框中更新。 有没有办法在填充位置选项后触发刷新到搜索​​框,以便它将拾取那些新生成的选项 这是我正在使用的HTML:

aud

这是城市选择字段

<div class="col-md-6">
  <div class="form-group">
    <label class="control-label col-md-4">Countries<span></span></label>
    <div class="col-md-8">
      <select class="form-control selectpicker chosen-select" name="country_id" id="country_id" data-show-subtext="true" data-live-search="true" required>
           <option value="">Select</option>
           <?php  foreach ($countries as $key => $value) { ?>
                <option value="<?php echo $value['id']; ?>"><?php echo  $value['name_en']; ?>
           </option>
           <?php } ?>
      </select>
      <span class="help-block"></span>
    </div>
   </div>
 </div>

此位置字段:

<div class="col-md-6">
  <div class="form-group">
    <label class="control-label col-md-4">Cities<span></span></label>
     <div class="col-md-8">
       <select class="form-control" name="city_id" id="city_id" required>
            <option value="">Select</option>
       </select>
       <span class="help-block"></span>
     </div>
   </div>
  </div>

现在这些是我填充这些字段的ajax调用:

<div class="col-md-6">
  <div class="form-group">
    <label class="control-label col-md-4">Location<span class=""></span></label>
       <div class="col-md-8">
         <div class="ui-widget">
         <?php echo form_error('location_id'); ?>
         <select id="cars_location" value="<?php echo 
                                            set_select('location_id'); ?>" type="text" class="form-control selectpicker " multiple name="location_id" data-show-subtext="true" data-live-search="true" required>
             <option value="">Select</option>
          </select>
         </div>
        <div class="omitted_location">

        </div>
       </div>
      </div>
     </div>

1 个答案:

答案 0 :(得分:2)

当ajax调用成功并且您为<option>获取新的<select>时,您正在插入它,但为了在引导小部件中反映这些更新,这是您的情况下的selectpicker,您需要使用selectpicker('refresh')刷新它。所以在loaction的情况下..

//Here i'm sending options to locations
//which isn't getting populated dynamically
$("#cars_location").html(msg); 
$('#cars_location').selectpicker('refresh'); // <-- add this