使用JavaScript更改select中的选项,而不失去选中状态
我试图用JavaScript和JQuery重新加载select的选项列表,但我需要保留以前选择的值 这是我的代码:使用JavaScript更改select中的选项,而不失去选中状态,javascript,jquery,Javascript,Jquery,我试图用JavaScript和JQuery重新加载select的选项列表,但我需要保留以前选择的值 这是我的代码: var temp = $('#SelectName').chosen().val(); select = document.getElementById('SelectName'); if (select.options.length > 0) { $('#SelectName').find('option').remove();
var temp = $('#SelectName').chosen().val();
select = document.getElementById('SelectName');
if (select.options.length > 0) {
$('#SelectName').find('option').remove();
}
for (var i = 0; i < result.length; i++) {
var option = document.createElement('option');
option.value = result[i].myIdVariable;
option.text = result[i].myTextVariable;
select.appendChild(option);
}
$('#SelectName').chosen(temp);
$('#SelectName').trigger('chosen:updated');
var temp=$('#SelectName').selected().val();
select=document.getElementById('SelectName');
如果(选择.options.length>0){
$('#SelectName')。查找('option')。删除();
}
对于(变量i=0;i
使用此代码,我失去了所有选择的值。我使用此代码解决:
var temp = $('#SelectName').val();
select = document.getElementById('SelectName');
if (select.options.length > 0) {
$('#SelectName').find('option').remove();
}
for (var i = 0; i < result.length; i++) {
var option = document.createElement('option');
option.value = result[i].myIdVariable;
option.text = result[i].myTextVariable;
select.appendChild(option);
}
$('#SelectName').val(temp);
$('#SelectName').trigger('chosen:updated');
及
以前:
var temp = $('#SelectName').chosen().val();
及
$('#SelectName').val(temp);
var temp = $('#SelectName').chosen().val();
$('#SelectName').chosen(temp);