如何在AJAX响应后刷新选择列表

时间:2015-12-07 21:20:18

标签: jquery ajax

我正在通过AJAx响应从数据库中填充select列表。 DOM正在正确更新,但单击它时列表仍为空。我尝试过这里的其他例子,但都没有帮助。

HTML:

<div class="modal" id="linkLocationModal" role="dialog">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header bg-success">
        <h4 class="modal-title" id="exampleModalLabel">Select New Location</h4>
      </div>
      <div class="modal-body">
        <form id="addLocationForm" action="/addProviderLocation" class="form-horizontal" method="post">
          <div class="form-group">
            <label class="col-sm-3 control-label" for="locationSelect">Location</label>
            <div class="col-sm-6">
              <select class="form-control" name="locationSelect" id="locationSelect" required multiple>
              </select>
              <input type="text" hidden id="h2providerid" name="h2providerid" value="" />
            </div>
            <div class="col-sm-3"></div>
          </div>
          <div class="form-group">
            <div class="col-sm-offset-3 col-sm-9">
              <button type="submit" class="btn btn-success">Link</button>
            </div>
          </div>
        </form>
      </div>
      <div class="modal-footer">
        <a class="btn btn-default" data-dismiss="modal">Close</a>
      </div>
    </div>
  </div>
</div>

的JavaScript

$('#linkLocationModal').on('show.bs.modal', function(event) {
  $.ajax({
    type: "POST",
    url: "/locations"
  }).done(function(html) {
    $('#locationSelect').html('');

    $.each(html, function(val, text) {
      $('#locationSelect').append($('<option></option>').val(text.id).html(text.locationname));
    });
  });
});

如果我尝试追加“on”事件之外的选择列表,则效果很好。我的目标当然是从db。中动态填充列表。

从ajax请求返回的数据: 2第二个测试位置 19林肯(McBee St) 16吉尔福德(Bellemeade中心) 24罗宾逊(戈德温大道) 5 Davidson(Grimes Blvd)

DOM:

<select class="form-control" name="locationSelect" id="locationSelect" required="" multiple="" data-fv-field="locationSelect" style="display: none;"><option value="2">Second Test Location</option><option value="19">Lincoln (McBee St)</option><option value="16">Guilford (Bellemeade Center)</option><option value="24">Robeson (Godwin Avenue)</option><option value="5">Davidson (Grimes Blvd)</option><option value="3">Mecklenburg (Charlotte East)</option></select>

1 个答案:

答案 0 :(得分:0)

我终于开始工作了。使用plugin,我需要使用提供的函数重建选择列表。循环后移动以下代码以附加:

$('#addLocationForm')
              .find('[name="locationSelect"]')
              .multiselect({
                enableFiltering: true,
                includeSelectAllOption: true,
                // Re-validate the multiselect field when it is changed
                onChange: function (element, checked) {
                  $('#addLocationForm').formValidation('revalidateField', 'locationSelect');
                }
              })
              .end();