Javascript 使用jQuery隐藏搜索函数中不匹配的选项

Javascript 使用jQuery隐藏搜索函数中不匹配的选项,javascript,php,jquery,html,Javascript,Php,Jquery,Html,我有多个选择的搜索功能: var SWAPLIST = {}; SWAPLIST.search = function(list, search) { $(list) .children() .prop('selected', false) .filter(function() { if (!search) { return false; } return $(this) .tex

我有多个选择的搜索功能:

var SWAPLIST = {};
SWAPLIST.search = function(list, search) {
  $(list)
    .children()
    .prop('selected', false)
    .filter(function() {
       if (!search) 
       {
         return false;
       }
       return $(this)
       .text()
       .toLowerCase()
       .indexOf(search.toLowerCase()) > - 1;
    })
   .prop('selected', true)
};
将其绑定到此事件:

$(document).ready(function(){
   $('.entitySearch').keyup(function() {
     var kind    = $(this).attr('kind');
     var left  = '.leftEntities[kind=' + kind +']';
     var right = '.rightEntities[kind='+ kind +']';

     SWAPLIST.search(left + "," + right, $(this).val());
   });
});
这是我的multiselect的一个示例:

<select class="leftEntities grid5" kind="<?php echo $firstKeyLeft;?>" multiple="multiple" size="10">     
  <option> a </option>
  <option> ab </option>
  <option> abc </option>
  <option> abcd </option>    
</select>   

我修改了您的示例标记,并编写了一些新的JS使其正常工作

在这里查看我的工作示例:

下面是示例中的JS:

$(function () {
    $('input[data-filter="example_select"]').on('keyup', function () {
        var $select_to_filter = $('[name="' + $(this).attr('data-filter') + '"]');
        var $move_hidden_options_to = $('select.hidden_options[for="' + $(this).attr('data-filter') + '"]');
        var filter_value = $(this).val();
        $select_to_filter.find('option').each(function () {
            if ($(this).text().indexOf(filter_value) == -1) {
                $(this).prependTo($move_hidden_options_to);
            }
        });
        $move_hidden_options_to.find('option').each(function () {
            if ($(this).text().indexOf(filter_value) !== -1) {
                $(this).prependTo($select_to_filter);
            }
        });
    });
});

你能分享相关的html吗当然,但这是非常多的,不仅仅是html,所以我会在这里添加一个相关html的链接。请看你能解释一下你想要什么吗我建议使用类似select2的东西来完成这一点。非常感谢,这就是我要找的!也可以选择过滤选项吗?@kinske不客气!在这里,我更新了我的示例,以便在过滤后选择可见选项。
$(function () {
    $('input[data-filter="example_select"]').on('keyup', function () {
        var $select_to_filter = $('[name="' + $(this).attr('data-filter') + '"]');
        var $move_hidden_options_to = $('select.hidden_options[for="' + $(this).attr('data-filter') + '"]');
        var filter_value = $(this).val();
        $select_to_filter.find('option').each(function () {
            if ($(this).text().indexOf(filter_value) == -1) {
                $(this).prependTo($move_hidden_options_to);
            }
        });
        $move_hidden_options_to.find('option').each(function () {
            if ($(this).text().indexOf(filter_value) !== -1) {
                $(this).prependTo($select_to_filter);
            }
        });
    });
});