如何在使用下拉列表过滤后保留多选框中的选定值

我目前有一个建筑物的下拉列表,可以过滤多选框,其中各个房间按其各自的建筑物分组。

一切都很好,除了当我在多选框中选择或预先选择了值并且我使用下拉列表过滤多选框时,它不允许所选项目保持不变。

EX:假设我通过Multi Box选择会计库内的两个房间

 105A ##Select 105B ##Select   fad zzz   155 156  

然后我用我的Dropdown(Ahmanson中心)过滤并得到……

  fad zzz  

这是正确的,除了我想保留或附加在使用下拉列表过滤之前选择的值。

  fad zzz   105A ###Keep Selected 105B ###Keep Selected  

有谁知道我怎么能用我的JavaScript做到这一点?

JAVASCRIPT

 $(function() { ###Gathers all rooms in Multi Select Box var originalRooms = $('#key_room_ids').html(); ###Filters Multi Box when the Dropdown menu changes $("#key_building_name").on("change",function() { $('#key_room_ids').html(originalRooms); if (this.value != "all") { ###Name of selected building in the Dropdown var building = $('#key_building_name :selected').text(); ###Removes all of the optgroup elements (and their options) that do not match the selected building. ###How can I also keep the optgroup element (and the options) that have been selected? $('#key_room_ids').find("optgroup:not([label='" + building + "'])").remove(); } }); }); 

形成

  '' }) do |f| %> ###Dropdown Filter  '- Please Select A Building To Filter The List Below -'}, { class: "form-control" } %> ###Multi Select Box Grouped by Building  "form-control"} %>  

这是你可以做的事情:

 $(function() { $("#filter").bind("keyup", function(e) { var filterText = $(e.target).val(); if (filterText === "") { $("optgroup").show(); } $("optgroup", $("select")).each(function(index, option) { if (!$(option).attr("label").includes(filterText)) { if ($("option:selected", $(option)).length === 0) { $(option).hide(); } } }); }); }); 
 select { height: 150px; margin-top: 15px; }