Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
364 views
in Technique[技术] by (71.8m points)

jQuery UI Autocomplete use startsWith

I'm using the jQuery UI Autocomplete with a local datasource (source: myArray). I want the autocomplete to propose only the results that start with the string entered instead of the default case-insensitive contains search. Is there a simple solution for this or do I have to provide my custom search/source callback?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

See this:

Match start word:

http://blog.miroslavpopovic.com/jqueryui-autocomplete-filter-words-starting-with-term

He overrides the autocomplete filter method. I use this and it works well.

// Overrides the default autocomplete filter function to search only from the beginning of the string
$.ui.autocomplete.filter = function (array, term) {
    var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex(term), "i");
    return $.grep(array, function (value) {
        return matcher.test(value.label || value.value || value);
    });
};

Match word:

Match startsWith of any word in the string.

e.g. "LHR london" is matched by "london"

var matcher = new RegExp("\b" + $.ui.autocomplete.escapeRegex(term), "i");

assert position at a word boundary (^w|w$|Ww|wW)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...