Javascript 在ajax模式下选择2 4.0初始值
我的页面上有以下选项:Javascript 在ajax模式下选择2 4.0初始值,javascript,jquery,ajax,jquery-select2,jquery-select2-4,Javascript,Jquery,Ajax,Jquery Select2,Jquery Select2 4,我的页面上有以下选项: <select><option value="1" selected="selected">Caption</option></select> 标题 我调用select2(v4.0)初始化: city.select2({ 阿贾克斯:{ 网址:, 数据:, 处理结果:, 缓存:真 }, escapeMarkup:函数(标记){return markup;}, 最小输入长度:0, templateResult:functio
<select><option value="1" selected="selected">Caption</option></select>
标题
我调用select2(v4.0)初始化:
city.select2({
阿贾克斯:{
网址:,
数据:,
处理结果:,
缓存:真
},
escapeMarkup:函数(标记){return markup;},
最小输入长度:0,
templateResult:function(repo){return repo.name;},
templateSelection:函数(repo){return repo.name;}
});
问题是select2正在重置默认选定值并显示空白字符串。有没有办法在select2 init上设置默认值?问题出在
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; }
});
city.select2({
阿贾克斯:{
网址:,
数据:,
处理结果:,
缓存:真
},
escapeMarkup:函数(标记){return markup;},
最小输入长度:0,
templateResult:function(repo){return repo.name | | repo.text;},
模板选择:函数(repo){return repo.name | | repo.text;}
});
这将解决您的问题,并正确显示初始选择。select2文档现在具有
基本上,为ajax配置select2,然后预先填充所需的对象。魔法是在最后一位,
.trigger()
完成的,这会导致select2拾取更改并进行渲染。我想您可能需要使用initSelection选项。我手头上没有一个有效的示例,但您可能希望为您的解决方案研究它。的可能重复
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; }
});
// 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
}
});
});