问题
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:
The
source
option takes arequest
andresponse
parameter. Basically, you manipulaterequest.term
(replace the dashes with an empty string) before comparing it with the list of valid values.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