简体   繁体   中英

Simple way to filter the list by input search value

I have following view to list the fruits and I can filter those by input text value

在此处输入图片说明

this is the code snippet for that

@Html.TextBoxFor(m => m.SearchKey, new {@id ="SearchKey" })    
@Html.ListBox("L", new MultiSelectList(Model.FruitList, "Id", "Name"), new { multiple = "multiple", id = "FruitList" })

Here filtering scenario I used following two options.

Option 1

            $(function() {
                $('#FruitList').filterByText($('#SearchKey'), true);
            }); 

            jQuery.fn.filterByText = function (textbox, selectSingleMatch) {

                return this.each(function ()
                {
                    var select = this;
                    var options = [];

                    $(select).find('option').each(function()
                    {
                        options.push({value: $(this).val(), text: $(this).text()});
                    });

                    $(select).data('options', options);

                    $(textbox).bind('change keyup', function()
                        {
                            var options = $(select).empty().scrollTop(0).data('options');
                            var search = $.trim($(this).val());
                            var regex = new RegExp(search,'gi');

                        $.each(options, function (i)
                        {
                            var option = options[i];

                            if (option.text.match(regex) !== null)
                            {
                                $(select).append($('<option>').text(option.text).val(option.value));
                            }
                        });

                        if (selectSingleMatch === true && $(select).children().length === 1)
                        {
                            $(select).children().get(0).selected = true;
                        }
                    });
                });
            };

Option 2

            $(function () {
                var fruitSelect = $("#FruitList"),
                    searchField = $("#SearchKey"),
                    options = FruitList.find("option").clone(); // clone into memory

                // generic function to clean text
                function sanitize(string)
                {
                    return $.trim(string).replace(/\s+/g, ' ').toLowerCase();
                }

                // prepare the options by storing the
                // "searchable" name as data on the element
                options.each(function ()
                {
                    var option = $(this);
                    option.data("sanitized", sanitize(option.text()));
                });

                // handle keyup
                searchField.on("keyup", function (event)
                {
                    var term = sanitize($(this).val()),matches;

                    // just show all options, if there's no search term
                    if (!term)
                    {
                        fruitSelect.empty().append(options.clone());
                        return;
                    }

                    // otherwise, show the options that match
                    matches = options.filter(function ()
                    {
                      return $(this).data("sanitized").indexOf(term) != -1;
                    }).clone();

                    fruitSelect.empty().append(matches);

                });
            });

            function rearrangeList(list)
            {
                $(list).find("option").sort(byValue).appendTo(list);
            }

But this seems more code line , is there any easy way to achieve this purpose ?

Without going for backend ajax call. How can I write a simple and less code jquery for filter this list by input search string

Let's assume the html generated is like this

<input type="text" id="filterText" />
<br/>
<select multiple>
  <option>apples</option>
  <option>apricots</option>
  <option>blueberry</option>
  <option>acai</option>
  <option>bananas</option>
  <option>cherry</option>
</select>

Then the js below does the filter

$('#filterText').on('keyup', function() {
    var filterWord = $(this).val().toLowerCase();
    $('select').find('option').show()
    $('select').find('option').not(':contains('+filterWord+')').hide()
});

Once a key is pressed on the input text, it automatically displays the options and then hides those ones that do not contain those characters

https://jsfiddle.net/a7u9fo9q/1/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM