【问题标题】:Append selected after ajax call在ajax调用后追加选择
【发布时间】:2017-07-03 20:05:08
【问题描述】:

我有一个 Select 2 下拉搜索功能。我正在尝试将 ajax 调用的结果作为选定/默认值加载。我不确定我哪里出错了?我需要在此处更改的语法是什么,以便当我单击我的模式时它会显示结果预设。

$(document).ready(function() {
  $('.editApptModal-button').click(function() {
    var appointmentID = $(this).attr('data-appointmentID');

    $('#editApptModal').find('input[name="appointmentID"]').val(appointmentID);
    $.ajax({
      type: 'ajax',
      method: 'get',
      url: '/ajax',
      async: false,
      dataType: 'json',
      success: function(response) {

        console.log(JSON.stringify(response));

        $.each(response.employees.data, function(key, value) {
          $('select').append($("<option selected></option>",
            //<HERE Selected is not working. 
            //If I remove selected results load in dropdown
            {
              value: value.id,
              text: value.name
            }));
        });

        $('#editApptModal').modal('show');
      },
      error: function(response) {
        alert('Could not displaying data' + response);
      }
    });

    $('#editApptModal').modal('show');
  });
});

<select multiple="multiple" name="employees[]" id="form-field-select-4" class="form-control search-select"> 
<option selected value=""></option>

【问题讨论】:

  • 我不确定,但如果不是多选,添加几个“选定”选项会破坏您的选择?
  • 这是一个多选。我已将其添加到问题中。

标签: javascript jquery ajax jquery-select2


【解决方案1】:

首先,您应该尝试只追加一次,因为这是一项繁重的操作。 通过直接设置属性似乎在这里工作。

var datas = [
  {value: 'toto', text: 'Toto'},
  {value: 'titi', text: 'Titi'}
];

var options = '';
$.each(datas, function(key, value) {
  options += '<option selected>'+value.text+'</option>';
});

$('#select').append(options);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select multiple id="select"></select>

【讨论】:

    【解决方案2】:

    您必须在完成后发出刷新命令。这里有一个快速的 sn-p 它为我的一个项目做同样的事情。 TransportRecord_TransportCarrierID 是我的选择元素的 ID。

                    $('#TransportRecord_TransportCarrierID').empty();
                    $.each(jsonResponse, function (key, item) {
                        var option = $('<option selected>').text(item.Text).val(item.Value);
                        $('#TransportRecord_TransportCarrierID').append(option);
                    });
                    $('#TransportRecord_TransportCarrierID').selectpicker('refresh');
    

    HTML

    <select class="form-control selectpicker" data-live-search="true" data-style="btn-defaultWhite" multiple="multiple" id="TransportRecord_TransportCarrierID" name="TransportRecord.TransportCarrierID">//your initial options</select>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-21
      • 2018-02-21
      • 1970-01-01
      • 2012-10-11
      • 1970-01-01
      • 2014-01-05
      • 1970-01-01
      • 2016-03-18
      相关资源
      最近更新 更多