Select2加载默认值使用远程数据的单选元素中的值
问题描述:
即时通讯使用jquery Select2,select2完美无缺。但是我想要什么时,页面加载默认值应该从控制器加载。Select2加载默认值使用远程数据的单选元素中的值
是的,我已经做过谷歌和是的这个问题已经发布了很多次,我不能相当让我的头围绕它..所以,这就是为什么我需要在这方面的帮助。
这里是选择2 JS代码:
/*----------- Select2 DropDown Common Script -------------------------*/
//For ServerSide Script
function commonSelect2(selector,url,id,text,minInputLength,placeholder){
selector.select2({
minimumInputLength:minInputLength,
placeholder:placeholder,
ajax: {
type:"post",
url: url,
dataType: 'json',
quietMillis: 100,
data: function(term, page) {
return {
term: term, //search term
page_limit: 10 // page size
};
},
initSelection : function (element, callback) {
var data = {id: element.val(), text: element.val()};
callback(data);
},
results: function(data, page) {
var newData = [];
$.each(data, function (index,value) {
newData.push({
id: value[id], //id part present in data
text: value[text] //string to be displayed
});
});
return { results: newData };
}
}
});
}
,在这里我是如何从PHP文件
{{*The Selector for Selecting the User Group*}}
var selector = $('#selectGroup');
var url = "{{base_url()}}admin/usersManageUsers/loadAllUserGroups/";
var id = "GroupID";
var text = "GroupName";
var minInputLength = 0;
var placeholder = "Select User Group";
commonSelect2(selector,url,id,text,minInputLength,placeholder);
//End of the CommonSelect2 function
我已经加入了initselection()
函数调用它,但我不知道如果我这样做写得对吗?
最后我在html select2隐藏的输入标记中添加了这个。
我试图在网上搜索,但看起来像我没有得到任何地方。
答
我的错误。 我在ajax里面定义了initSelection。应该在ajax之外定义它。
现在阿贾克斯之后定义initSelection()
ajax: {
type:"post",
url: url,
dataType: 'json',
quietMillis: 100,
data: function(term, page) {
return {
term: term, //search term
page_limit: 10 // page size
};
},
results: function(data, page) {
var newData = [];
$.each(data, function (index,value) {
newData.push({
id: value[id], //id part present in data
text: value[text] //string to be displayed
});
});
return { results: newData };
}
},
initSelection : function (element, callback) {
var data = {id: element.val(), text: element.val()};
callback(data);
}