开发者

How to edit input into jQuery Autocomplete before search?

开发者 https://www.devze.com 2023-03-01 19:06 出处:网络
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

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.


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/

0

精彩评论

暂无评论...
验证码 换一张
取 消