2011-07-25 58 views
0

想象实例选择选项,一会儿动态通过其他SELECT选择

<select> 
    <option value="volvo">Volvo</option> 
    <option value="saab">Saab</option> 
    <option value="mercedes">Mercedes</option> 
    <option value="audi">Audi</option> 
</select> 

除了另一个相同的选择框

<select> 
    <option value="volvo">Volvo</option> 
    <option value="saab">Saab</option> 
    <option value="mercedes">Mercedes</option> 
    <option value="audi">Audi</option> 
</select> 

我应该有另一种选择框,试想一下,“沃尔沃”和“萨博“在这些选择框中被选中,则(第三)结果选择框应该包含选项”沃尔沃“和”萨博“。

似乎简单的权利?当有人改变他们的答案时,它变得更加复杂,并且像我如何动态地将其扩展到任何数量的选择框(即 - 想象我有两个以上的选择框)开始出现,并且通常是DOM,以及也许jQuery是不是友好的,因为也许当谈到这些样的东西是应该的,所以我想问你的智慧的StackOverflow

什么是检索一组的选择框的当前值的最洁净的方式和使用这些动态作为另一个选择框的选项

回答

1

如果你的名字你用的ID firstsecond,最后一个third第一和第二选择框..

// Get our select lists 
var first = $("#first"); 
var second = $("#second"); 
var third = $("#third"); 

// Merge the selections from the first and second lists 
function mergeSelections() { 
    // Get the list elements 
    var firstSelections = $("option:selected", first); 
    var secondSelections = $("option:selected", second); 

    // Clear the destination list 
    third.clear(); 

    // Merge lists, add each selected element 
    $.merge(firstSelections, secondSelections).each(function(i, item) { 
     // Clone the original, add to the third list 
     $(item).clone().appendTo(third); 
    }); 
} 

// Set up actions 
first.change(mergeSelections); 
second.change(mergeSelections); 
+0

你是男人安德鲁Koester的神。 –

1

试试这个

$("select:first option");//This will give you options dom element array and you iterate through this and create options for other select element. 
+0

这应该是'选项:selected',不'options' – Jess

+0

@Andrew - 他需要所有的选择,而不仅仅是选择一个。但是,它应该只是选择,而不是选项,这是一种感谢让我知道的类型。 – ShankarSangoli