在不丢失选定索引的情况下用数据重新填充 select2
Repopulate select2 with data without losing selected index
我的页面上有很多 select2
个项目,里面全是项目。
我从模态添加新数据,并在模态关闭后用新数据重新填充所有 select2
。我发现 select2
失去了选择的价值!!
这是我使用的代码:
$.get(callPath, { }, function(dataDropDown) {
$('.'+ refInput).each(function(){
$(this).html(dataDropDown);
$(this).trigger("change");
});
// $("'" + refInput + "'").html(dataDropDown);
})
我想在不丢失所选值的情况下重新填充元素
您可以在 Ajax 请求函数中传递选定的值。像这样:
var selectedId = $('#myselect').val();
$.get(callPath, { }, function(dataDropDown, selectedId) {
$('.'+ refInput).each(function(){
$(this).html(dataDropDown);
$(this).trigger("change");
});
$('#myselect').val(selectedId);
// $("'" + refInput + "'").html(dataDropDown);
})
$.get(callPath, { }, function(dataDropDown) {
$('.'+ refInput).each(function(){
// get current value:
var selected = $(this).select2('val');
$(this).html(dataDropDown);
$(this).trigger("change");
// set it after repopulate:
$(this).select2('val', selected);
});
})
我的页面上有很多 select2
个项目,里面全是项目。
我从模态添加新数据,并在模态关闭后用新数据重新填充所有 select2
。我发现 select2
失去了选择的价值!!
这是我使用的代码:
$.get(callPath, { }, function(dataDropDown) {
$('.'+ refInput).each(function(){
$(this).html(dataDropDown);
$(this).trigger("change");
});
// $("'" + refInput + "'").html(dataDropDown);
})
我想在不丢失所选值的情况下重新填充元素
您可以在 Ajax 请求函数中传递选定的值。像这样:
var selectedId = $('#myselect').val();
$.get(callPath, { }, function(dataDropDown, selectedId) {
$('.'+ refInput).each(function(){
$(this).html(dataDropDown);
$(this).trigger("change");
});
$('#myselect').val(selectedId);
// $("'" + refInput + "'").html(dataDropDown);
})
$.get(callPath, { }, function(dataDropDown) {
$('.'+ refInput).each(function(){
// get current value:
var selected = $(this).select2('val');
$(this).html(dataDropDown);
$(this).trigger("change");
// set it after repopulate:
$(this).select2('val', selected);
});
})