select2 插件编辑时设置默认值

时间:2021-07-23 15:06:00
function htDate(selectCustomerId, val) {
    var customerId = selectCustomerId;
    var values = val;
    ajaxJson('GET', webroot + "/customer/getOptionList", '', function(err, rsp) {
        if (rsp.code == 200) {
            var text = rsp.result;
            customerId.select2({
                placeholder: "请选择客户",
                allowClear: true,
                language: "zh-CN",
                width: '410px'
                    // data:text,
            });

            //绑定Ajax的内容
            customerId.empty(); //清空下拉框
            $.each(text, function(i, item) {
                customerId.append("<option value='" + item.id + "'>&nbsp;" + item.name + "</option>");
            });
            /*设置默认值*/
            $(customerId).val(values);
        } else {
            // hint(rsp.message);
            console.log(rsp);
        }
    })
}
//使用
var customer = $("#customerId");
var val = data.customerId;
htDate(customer, val);

 ajax 请求数据的时候

 
 

var jz_roomId = $('#jz_roomId');
$(jz_roomId).select2({
dropdownParent: $(".customerRoomIdModal"),
ajax: {
url: webroot + '/spaceRoom/listRoom',
dataType: 'json',
delay: 250,
type: 'POST',
contentType: "application/json",
data: function(params) {
var paramss = {
code: params.term
};
return JSON.stringify(paramss);
},
processResults: function(data, params) {
//请求接口返回数据
params.page = params.page || 1;
return {
results: data.result
};
},
cache: true
},
//options
language: "zh-CN",
placeholder: '请输入房间号',
allowClear: true,
width: '300px',
//键盘选择事件
escapeMarkup: function(markup) {
return markup;
},
minimumInputLength: 1,
templateResult: formatRepo,
templateSelection: formatRepoSelection
});


//
再次加载默认值. 赋值.
var roomName = $(e).parent().parent().parent().find('td').eq(1).text();
var option = new Option(roomName, editResult.roomId, true, true); 
$('#jz_roomId').append(option);
$('#jz_roomId').trigger('change');//使用这个方法显示到select2上.