简体   繁体   中英

Autocomplete show all results

Collect data from page format.json .

In JS I have:

$('input[name="q"]').autoComplete({
    source: function(term, response){
        $.getJSON('/search.json', { q: term }, function(data){ response(data); });
    }
});

For autocomplete I use this plugin .

What is responsible for the output?

I have in the autocomplete drop all the names. To fall out only need to apply. it is necessary to drop only those which coincide.

Is responsible for it .indexOf(term) ? what to use?

在此处输入图片说明

The screen shows all the results (which have match and those who do not have a match). Need to see only those that have a match.

Being you're getting the data from a JSON file you'll have to do the filtering on the client side. The way that it would work with an actual AJAX request to a server, you'd do the filtering on the server to only return the data you need (that's why you send the query term as a parameter).

So you will need to change your code to look like this:

$('input[name="q"]').autoComplete({
    source: function (term, response) {
        $.getJSON('/search.json', function (data) {
            term = term.toLowerCase();
            var matches = [];
            for (i = 0; i < data.length; i++)
                if (~data[i].toLowerCase().indexOf(term)) matches.push(data[i]);
            response(matches);
        });
    }
});

You may need to do something different depending on what your data structure looks like but I'm assuming it's an array of strings

EDIT

If you want to limit your matches you can do it in the for loop rather than in the last line, this will be better for performance as it won't have to loop around once you've got 5 matches

$('input[name="q"]').autoComplete({
    source: function (term, response) {
        $.getJSON('/search.json', function (data) {
            term = term.toLowerCase();
            var matches = [];
            for (i = 0; i < data.length; i++)
                if (~data[i].toLowerCase().indexOf(term) && matches.length == 4) {
                    matches.push(data[i]);
                    break;
                }
            response(matches);
        });
    }
});

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