[英]Remove item from second dropdown based on selection in First using Javascript
我有四個下拉菜單,我正在手動填充它們。
現在,我想添加一個javacsript,當我選擇第一個下拉選項時,然后在第二個第三個,第四個下拉菜單中,可以刪除該項目或選項。
同樣的流向第二,第三和第四,依此類推。
我正在提供代碼,但到目前為止,它仍然無法正常工作。
我只是在嘗試第一個階梯,即選擇了第一個階梯中的選項,然后從第二,第三和第四下拉菜單中刪除了項目。
function RemoveItems(){
var List1 = document.getElementById("ddlSortField");
var sortList1 = List1.options[List1.selectedIndex].text;
var List2 = document.getElementById("ddlSortField2");
var sortList2 = List2.options[List2.selectedIndex].text;
List2.options.remove(sortList1);
var List3 = document.getElementById("ddlSortField3");
var sortList3 = List3.options[List3.selectedIndex].text;
List3.options.remove(sortList2);
var List4 = document.getElementById("ddlSortField4");
var sortList4 = List4.options[List4.selectedIndex].text;
List4.options.remove(sortList3);
}
使用jQuery刪除選項
$(document).ready(function(){
$('#ddlSortField').change(function(){
var index = $("#ddlSortField option:selected").val();
$('#ddlSortField2 option:eq(' + index + ')').remove();
$('#ddlSortField3 option:eq(' + index + ')').remove();
$('#ddlSortField4 option:eq(' + index + ')').remove();
});
});
請注意,在您的html中,您的選項值必須像這樣:
<select id="ddlSortField">
<option value="1">test1</option>
<option value="2">test2</option>
<option value="3">test3</option>
</select>
<select id="ddlSortField1">
<option value="1">test1</option>
<option value="2">test2</option>
<option value="3">test3</option>
</select>
您可以使用以下代碼: jsFiddle 。
基本上,您首先將change
事件綁定到每個列表,並且當您更改值時,在...之后將這些元素隱藏在所有列表中。
我制作的內容與@Muhammad Omair的稍有不同,該內容更具動態性。 請注意,這是jQuery
var removeSelection = function(select) {
$('select').filter(':not(#' + select.attr('id') + ')').each(function() {
var index = select.find(':selected').index();
$(this).find('option:eq(' + index + ')').remove();
});
};
$(function() {
$('select').change(function() {
removeSelection($(this));
});
});
這是它的jsfiddle http://jsfiddle.net/cA3F9/
在您的代碼中:
> function RemoveItems(){
按照慣例,以大寫字母開頭的變量名稱保留給構造函數使用,因此:
function removeItems() {
> var List1 = document.getElementById("ddlSortField");
> var sortList1 = List1.options[List1.selectedIndex].text;
因此sortList1將是一個字符串。
> var List2 = document.getElementById("ddlSortField2");
> var sortList2 = List2.options[List2.selectedIndex].text;
> List2.options.remove(sortList1);
選項集合的remove方法采用單個參數,該參數是選項之一的索引。 您尚未顯示sortList1的值或List2有多少個選項。 請注意,選項集合是實時的,因此,如果刪除選項,則可能會調整其他選項的索引,以使它們從0到options.length - 1
連續。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.