2016-10-03 133 views
0

我有2個選擇框,第二個顯示基於第一個框中的類別的所有選項的子集。第二個框包含ID和名稱,其中選項值等於ID。我已經過濾了我感興趣的ID並將它們放在一個數組中。每次都會更改,並且可能會有不同的大小(按組篩選所有用戶)。我想要做的是對完整選項進行克隆,然後僅顯示那些身份證(或值)存在的人。因此,將過濾值的數組與完整集進行比較。我確實看到了一些刪除選項的方法,但是大多數方法一次只能處理一個值或固定值,所以它並不完全符合我的需要,而且我也無法弄清楚如何執行最後一步!如下所示:如何根據動態值刪除多個選擇選項

<select id = 'doctor_select' > 
<option value = '1' > John Doe </option> 
<option value = '2' > Jane Doe </option> 

....等

編輯:通過隱藏所有,並做了每個循環,使我需要的人解決了現在。

+0

您是否試圖將ID映射到選項?你只需要與id相匹配的選項?你會怎麼看,與ID有關的期權價值? – 2016-10-03 23:23:57

+0

這些值已經是用戶ID,並顯示其名稱。過濾的用戶數組包含所有正在搜索的組中的所有id,因此我只想在總列表中顯示這些選項。 – nick

+0

數組在哪裏?目標還不是很清楚 – charlietfl

回答

1

我不會這樣做,但你可以克隆原來的組合,只需從DOM中刪除不必要的選項。就像:

var newDoctorSelect=$("#doctor_select").clone(); 
$(newDoctorSelect).children("option").each(function() { 
    if(some condition) $(this).remove(); 
}); 
$("#somewhere").append(newDoctorSelect); 

但我建議要麼使用AJAX或將選項存儲在一個對象中,並在需要時填充選擇。

var optionsByCategory={ 
    "1":{"1":"One","3":"Three"}, 
    "2":{"2":"Two"} 
}; 

$("#categorySelect").on("change",function() { 
    var options=optionsByCategory[$(this).val()]; 
    //OR some AJAX call to retreive the options from the server instead 
    $("#doctor_select option").remove(); 
    for(var k in options) $("#doctor_select").append($("<option>").val(k).text(options[k])); 
}); 
0

你可以這樣做:

var options = getElementsByTagName("option"), 
    elem, 
    length = options.length; 

for (var i = 0; i<length; i++) { 
    if (!((elem = options[i]).value === IDYouWantToMatch)); elem.parentNode.removeChild(elem); 
} 
0

我想你想要像下面這樣使用filter()

var $sel = $('#doctor_select'), 
    $opts = $sel.children(); 

var $filteredOpts = $opts.clone().filter(function(){ 
    return someArray.indexOf(this.value)>-1; 
}) 
$sel.empty().append($filteredOpts); 

存儲的$opts現在可以重新用於未來的變化

相關問題