简体   繁体   中英

Custom filter for html datalist

I have the following form:

 <html> <body> <input type="text" list="test"> <datalist id="test"> <option>apple orange grape</option> <option>apple blueberry grape</option> <option>blueberry strawberry raspberry</option> </datalist> </body> </html>

The normal behavior is that the list of options in the dropdown box only lists options that contain the string typed by the user. So if the user types "apple" the first two options are displayed.

I want to use a custom filter, so if the user types multiple words it searches separately for each word - eg if they type "apple grape" the first two options should be displayed. Currently no options would be listed, because none of the options contain the string "apple grape".

Is this possible? I've found https://selectize.github.io/selectize.js/ which I think will do what I want and I think Bootstrap's autocomplete library will too but I was hoping I could do this with plain HTML/JS.

e: I think this is another way to describe what I'm trying to do:

 var a = ["apple orange grape", "apple blueberry grape", "blueberry strawberry raspberry"]; function filter(t) { var filterTerms = t.value.split(" "); var select = document.getElementById("select"); select.innerHTML = ""; for (var i = 0; i < a.length; i++) { var match = true; for (var j = 0; j < filterTerms.length; j++) { if (a[i].indexOf(filterTerms[j]) == -1) { match = false; } } if (match) { select.appendChild(new Option(a[i], a[i])); } } }
 <input type="text" id="filtertest" onkeyup="filter(this);"> <select id="select"> </select>

That JS makes it so the select only has options from the array a which match the filter in the text input. I want to combine the text input and select (like a text input with a datalist ).

What you want to do does not make a lot of sense. If the user types "apple grape" what is the script supposed to do while typing? Should it start searching with "appl" already, or how is it supposed to know you finished typing and want to look for the string (without a "search now" button).

Based on jquery you could narrow a list while typing like that

$("document").ready(function () {

    $("#InputBox").on("keyup", function () {
        var searchText = $(this).val();
        searchText = searchText.toLowerCase();
        searchText = searchText.replace(/\s+/g, '');
        $('#myList > li').each(function(){
            var currentLiText = $(this).text(),
                showCurrentLi = ((currentLiText.toLowerCase()).replace(/\s+/g, '')).indexOf(searchText) !== -1;

            $(this).toggle(showCurrentLi);

        });
    });
    inactivityTime();
});

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