我尝试和你一样直接在dataInit函数中使用select2(不同的是我使用的是ajax数据源),看起来不错但是不能正常工作:
- 值无法发送到服务器。
- 选择一行 -> 编辑,但 select2 未使用旧值初始化。
最后我放弃了这个方法,尝试使用edittype:'custom'
colModel:[
{name:'model_id',label:'mID',
hidden: true,
hidedlg: true, // the hidden model_id column
search: false, // used for offer id info to select2
},
{name:'model',label:'model',width:150,
editable:true,
edittype:'custom',
editoptions:{
custom_element: myselect2elem,
custom_value: myselect2value,
dataInit: myselect2init('180','chose model','search/servermodel','model_id','model'),
},
editrules:{
edithidden: true,
required: true,
},
},
我定义了三个函数:
- myselect2elem(value, options) // 初始化一个公共元素
- myselect2value(elem, operation, value) // 获取|设置元素的值
- myselect2init(width,holder,url,opt,cel_name_id,cel_name) //初始化元素使用select2
详情
function myselect2elem(value, options) {
var el = document.createElement("select");
el.value = value;
return el;
}
function myselect2value(elem, operation, value) {
if(operation === 'get') {
return $(elem).val();
} else if(operation === 'set') { // this doesn't work,
$(elem).value=value; // I don't know whether have side effect
}
}
function myselect2init(width,holder,url,cel_name_id,cel_name){
var option = {
width: width,
placeholder: holder,
ajax: {
url: url,
/*
the other ajax configuration option that only selet2 used
*/
},
}
return function(element) {
$(element).children(".customelement").select2(option)
// do the init 'set' operation that previous function should do
selRowId = $(this).jqGrid ('getGridParam', 'selrow'),
celId = $(this).jqGrid ('getCell', selRowId, cel_name_id);
celValue = $(this).jqGrid ('getCell', selRowId, cel_name);
if (celValue){
var newOption = new Option(celValue, celId, true, true);
$(element).children(".customelement").append(newOption).trigger('change');
}
}
}
感谢您对此提出的问题,感谢@Oleg 的回答。
我希望我的回答可以帮助到其他人