2010-04-02 116 views
3

我有n個下拉式選單,像這樣:如何使用jquery從select元素中刪除選項?

<select id="select1"> 
    <option>1</option> 
    <option>2</option> 
    <option>3</option> 
</select> 

<select id="select2"> 
<option>1</option> 
<option>2</option> 
<option>3</option> 
</select> 

具有相同的選項。所有的選擇都應該是唯一的,所以一旦在一個組合框中選擇了該選項,就應該將其從其他選項中移除。因此,如果用戶在select1中選擇「1」,則select2中將只有選項「2」和「3」。

現在,jQuery disable SELECT options based on Radio selected (Need support for all browsers)提供了一個很好的解決方案,但我該如何修改此選項而不是單選按鈕?

回答

6

這是你的意思嗎?僅在第一<select>

$("select").each(function() { 
    var select = $(this); 
    select.children("option").each(function() { 
    $('select').not(select).children("option[value=" + this.value + "]").remove(); 
    }); 
}); 

這將刪除所有的複製,讓他選擇:

這將消除一切從#select2這是在#select1

$("#select2 option").each(function() { 
    if($("#select1 option[value=" + this.value + "]").length) 
     $(this).remove(); 
}); 

這裏的另一個替代方案,刪除所有重複它發現它。

更新您的評論:

$("#select1").change(function() { 
$("#select2 option[value=" + $(this).val()+ "]").remove(); 
}); 
+0

謝謝,但我只需要刪除選定的元素。因此,如果用戶在select1中選擇「1」,則select2中將只有選項「2」和「3」。 – 2010-04-02 12:15:43

+0

@Lapa - 增加了一個選項,你可以看到它在這裏工作:http://jsfiddle.net/tdKUP/ – 2010-04-02 12:20:26

+0

+1刪除我的答案,因爲你的覆蓋它很好:)但我認爲在你的替代方法,你應該也可以使用'change'而不是'each' – 2010-04-02 12:23:25

1

或者,如果選擇具有相同順序的相同選項。

$('select').change(function() { 
    var selectedIndex = $(this).find(':selected').index();  
    $('select').not(this).find('option:nth-child(' + selectedIndex + ')').remove(); 
)}; 

我認爲這種方式更快(但不太容易閱讀)。

+0

這不像你想象的那樣:)一旦你刪除第一個元素,順序不再是相同的,你的索引關閉:) – 2010-04-02 12:27:22

+0

公平點..好的,如果你使用它雖然一次.. :) – Alistair 2010-04-02 12:40:03

相關問題