2011-06-09 56 views
0

大脑不能正常工作。有人帮我填补这里的空白。jquery,javascript,更新焦点下拉列表选项,但保留选定的值

需要选择当前选定的值,重新填充选项,然后选择之前的选择(如果它仍在列表中)。

为了方便起见,新值和先前选定的值将具有相同的名称属性,假定它在更新后仍在列表中,并且名称对于选项列表将始终是唯一的。

//assume Options is a globally defined var for this example with format: 
// [{"display":"something", "value": "something's value"}, etc.. ] 
function LazyLoadOptionsIntoSelect($select, options) 
{ 
    //get current option 


    //repopulate options 
    $select.html(""); 
    $("<option>").text("--Select a File--") 
       .appendTo($select); 
    $.each(options, function() 
    { 
     var item = this; 
     $("<option>").attr("name", function() { return item.display; }) 
       .val(function() { return item.value; }) 
       .text(item.display) 
       .appendTo($select); 
    }); 

    //select previously selected option if still in list 

} 

$(".lazyloadedselect", "#context").live("focus", function() 
{ 
    LazyLoadOptionsIntoSelect($(this), Options); 
}); 

编辑:错在我的代码,无关的问题,但仍然是错误的

+0

huuuuuuh ..... hm,我的工作不太好! – 2011-06-09 16:09:15

回答

0

如果该选项保持相同值的属性:

//get current option 
var theOption = $select.val(); 

后来......

//select previously selected option if still in list 
$select.val(theOption); 

编辑

你需要修复的错误在你的人口的代码,因为没有这些选项确实有值的属性,这可能是为什么你不能正确设置选择的值:

$.each(options, function(index, item) { 
    $("<option>") 
     .attr("value", item.display) 
     .text(item.display) 
     .appendTo($select); 
}); 

请注意name不是选项元素的标准属性。

+0

我首先尝试了一下,它突出显示了现在打开的下拉菜单中的选项,但将第一个选项显示为值。也许与命令有关的一切都被解雇了? – 2011-06-10 14:24:27

+0

我之前做过的克隆表单并保留下拉列表的值,但在这种情况下不起作用。 – 2011-06-10 14:27:26

+0

@Patrick:我已经添加了一个编辑,它在原始代码的方法中显示了一个错误,用于填充选项,以防止新选项具有与它们相关联的值,还会阻止您使用先前选择的项目更新选择值。 – lsuarez 2011-06-10 15:38:06

相关问题