How to edit input into jQuery Autocomplete before search?

时光毁灭记忆、已成空白 提交于 2020-01-04 01:19:30

问题


I have an autocomplete box that (for the purposes of this example, since it's a simple example) returns a list including social security numbers. These have dashes in them for readability. I want to modify the autocomplete so that if I put in "123456789" or "123-45-6789", it will find the same entry in the autocomplete, without having to add both styles to the autocomplete source. I've been looking at adding a callback to search, but I'm drawing a blank on exactly how to accomplish this.

If I were using a search that pulled from an AJAX source, I could simply trim the input server-side and return whatever results I wanted. However, for speed's sake, I've pre-loaded all of the data into the Javascript, so that option's out.

Basically, I want to know how to trim dashes off autocomplete input before comparing it to the stored data (and, preferably, comparing it to a copy of the stored data also with dashes trimmed). There's almost zero documentation on how to use the search: option, so I'm hoping someone can help.


回答1:


One way to do this would be to provide a function to the source option of autocomplete:

var ssn = ['123-45-6789', '333-44-5543', '111-34-9696', '555-99-5323'];

$("#ssn").autocomplete({
    source: function(request, response) {
        /* Remove the dashes from the search term: */
        var term = request.term.replace(/-/g, '');
        var matcher = new RegExp($.ui.autocomplete.escapeRegex(term), "i");

        response($.map(ssn, function(el) {
            /* Remove dashes from the source and compare with the term: */
            if (matcher.test(el.replace(/-/g, ''))) {
                return el;
            }
        }));
    }
});

Here's what's going on:

  1. The source option takes a request and response parameter. Basically, you manipulate request.term (replace the dashes with an empty string) before comparing it with the list of valid values.

  2. Then, call the response function with the correct results. This example uses $.map to return a list of matches, comparing the term to each item in the list (without the "-").

Here's a working example: http://jsfiddle.net/andrewwhitaker/r4SzC/



来源:https://stackoverflow.com/questions/5833688/how-to-edit-input-into-jquery-autocomplete-before-search

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!