I’ve come upon a very frustrating bug in my jquery autocomplete code. I’m working on a book catalogue for a small library project. The autocomplete is used to aid the user in searching by subject tag or by title.
Here’s the code (currently being executed on $(document).ready();)
var autoData = [];
$.get('/search_bar', function(data){
autoData = $.makeArray(data);
console.log(autoData);
});
$("#search").autocomplete({
source: function(req, responseFn){
var re = $.ui.autocomplete.escapeRegex(req.term);
var matcher = new RegExp("(?:^| )" + re, "gi");
var a = $.grep(autoData, function(item, index){
return matcher.test(item);
});
responseFn(a);
},
minLength: 2
});
To focus in on the problem, I’ve limited the response from the server to a set of 3 titles which should all be returned by starting to type “pag….”
console.log(autoData) => ["Pages africaines 1", "Pages africaines 2", "Pages africaines 3"]
However, jQuery autocomplete only suggests “Pages africaines 1” and “Page africaines 3”, not (as I’d expect) “Page africaines 2” as well, unless you type out the entire title “Pages africaines 2” (at which point it appears as the only suggestion, as one would expect).
I’ve tested the RegExp/$.grep on the array above, and it seems to work fine:
autoData = ["Pages africaines 1", "Pages africaines 2", "Pages africaines 3"]
$.grep(autoData, function(item, index){ return RegExp("(?:^| )pages", "gi") })
=> ["Pages africaines 1", "Pages africaines 2", "Pages africaines 3"]
Any insight? The $.get() receives a json-encoded response from my rails backend, e.g.:
def search_bar
output = Book.search('pages').map{|bt| bt.title }
render :json => output.to_json
end
(where i’ve limited the autocomplete to the above example to debug). However, in the Chrome javascript console, autoData is definitely an array object as expected.
Thanks in advance!
(Note: The reason i’m using the above RegExp with “(?:^| )” instead of a word-boundary match like “\b” is because there are often unicode/accented characters in the titles, which seems to break with a “\b” match.)
Replace:
With: