在ajax模式下选择2 4.0初始值

问题描述 投票:1回答:2

我的页面上有以下选择:

<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上设置默认值?

javascript jquery ajax jquery-select2 jquery-select2-4
2个回答
4
投票

问题出在你的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; }
});

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


1
投票

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获取更改并渲染它。

© www.soinside.com 2019 - 2024. All rights reserved.