我通过以下方式初始化了select2:
$('#bookingResource').select2({
placeholder: "Select Resource",
minimumInputLength: 0,
multiple: true,
allowClear: true,
data: function() {
return {results: sections };
}
});
Sections是一个对象,其中包含select2使用的id
和text
键。
我只需要使用另一个对象的ID预选一个值。
$('#bookingResource').select2("val", object.resourceID);
我想我需要使用initSelection
函数,但我不确定如何制定它以便我可以在section对象中返回与ID对应的文本...
当我尝试使用Select2中显示的以下initSelection示例并调用.select2("val"...
时,我根本没有输出。
initSelection : function (element, callback) {
var data = [];
$(element.val().split(",")).each(function () {
data.push({id: this, text: this});
});
callback(data);
}
答案 0 :(得分:1)
我认为initSelection
的{{3}}在此问题上并不清楚。关键是要注意initSelection
和
在The function will only be called when there is initial input to be processed之后,我注意到initSelection
在以下时间被调用:
.select2('val', $preselect_non_empty_value)
被调用,或value
属性。根据您检索sections
数据的方式,我的testing可能会也可能不会回答您的问题。第一个select2
调用.select2('val', 4)
将4设置为对象的预选ID。第二个select2
只使用element.val()
从HTML属性中提取值。
此外,我到目前为止看到的initSelection
上的大多数示例似乎都希望HTML元素包含一些初始值。否则,他们会做一些AJAX的事情。例如,
var id=$(element).val();
if (id!=="") {
$.ajax($some_url, {
//...
}).done(function(data) {
callback(data); // data must be a single object
});
}
希望这有帮助。