2011-07-25 57 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