【问题标题】:Select2 4.0 initial value in ajax modeajax模式下select2 4.0初始值
【发布时间】:2015-08-01 21:32:29
【问题描述】:

我的页面上有以下选择:

<select><option value="1" selected="selected">Caption</option></select>

我调用 select2 (v 4.0) init:

city.select2({
    ajax: {
        url: <...>,
        data: <...>,
        processResults: <...>,
        cache: true
    },
    escapeMarkup: function(markup){ return markup; },
    minimumInputLength: 0,
    templateResult: function(repo){ return repo.name; },
    templateSelection: function(repo){ return repo.name; }
});

问题是 select2 正在重置默认选定值并显示空白字符串。有没有办法在 select2 init 上设置默认值?

【问题讨论】:

  • 我认为您可能想要使用 initSelection 选项。我没有手头的工作示例,但您可能想研究一下您的解决方案。

标签: javascript jquery ajax jquery-select2 jquery-select2-4


【解决方案1】:

问题出在您的 templateSelection 方法中,因为您期望 name 属性出现在您的数据对象上。除了现在需要 text 并且如果重新映射它就不需要该方法之外,您还没有处理数据对象具有 text 属性的情况。

city.select2({
    ajax: {
        url: <...>,
        data: <...>,
        processResults: <...>,
        cache: true
    },
    escapeMarkup: function(markup){ return markup; },
    minimumInputLength: 0,
    templateResult: function(repo){ return repo.name || repo.text; },
    templateSelection: function(repo){ return repo.name || repo.text; }
});

这应该可以解决您的问题并正确显示初始选择。

【讨论】:

  • 终于有人找到了我想要的解决方案!谢谢!
【解决方案2】:

select2 文档现在有一个example of how to do this

// Set up the Select2 control
$('#mySelect2').select2({
  ajax: {
    url: '/api/students'
  }
});

// Fetch the preselected item, and add to the control
var studentSelect = $('#mySelect2');
$.ajax({
  type: 'GET',
  url: '/api/students/s/' + studentId
}).then(function (data) {
  // create the option and append to Select2
  var option = new Option(data.full_name, data.id, true, true);
  studentSelect.append(option).trigger('change');

  // manually trigger the `select2:select` event
  studentSelect.trigger({
    type: 'select2:select',
    params: {
      data: data
    }
  });
});

基本上,为 ajax 配置 select2,然后预填充所需的对象。魔术在最后一点完成,.trigger() 导致 select2 获取更改并呈现它。

【讨论】:

    猜你喜欢
    • 2017-06-06
    • 1970-01-01
    • 2015-04-28
    • 2023-03-03
    • 2016-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多