简体   繁体   English

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

[英]Select2 4.0 initial value in ajax mode

I have the following select on my page: 我的页面上有以下选择:

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

I call select2 (v 4.0) init: 我将其称为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; }
});

The problem is that select2 is resetting default selected value and showing blank string. 问题在于select2正在重置默认选择值并显示空白字符串。 Is there any way to set default value on select2 init? 有什么办法可以在select2 init上设置默认值?

The issue was in your templateSelection method, as you are expecting a name property to be on your data object. 问题出在您的templateSelection方法中,因为您希望name属性位于数据对象上。 Aside from the fact that text is now required and you wouldn't need the method if you re-mapped it, you aren't handling the case where the data object has a text property. 除了现在需要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; }
});

This should fix your issue and display the initial selections properly. 这样可以解决您的问题,并正确显示初始选择。

The select2 docs now have an example of how to do this . select2文档现在有一个如何执行此操作示例

// 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
    }
  });
});

Basically, configure select2 for ajax and then pre-fill with the desired object. 基本上,为ajax配置select2,然后预填充所需的对象。 The magic is done in the last bit, .trigger() which causes select2 to pick up the change and render it. 魔术是在最后一位.trigger() ,它使select2拾取并呈现更改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM