Occasionally you’ll need to create some sort of auto-complete field. While you could power this entirely via AJAX requests on a per-character basis, with limited resources, you may want to look at this alternative.
Essentially you’ll create a javascript array containing allowed values. Whenever a user types in some characters, we can use some regex coupled with a quick iteration to see if whatever the user entered is valid. If it is, we can easily return the matched values.
The function below is written in straight JavaScript. I monitor my keypress events via jQuery, but any way you want to do it is fine. Just make sure you call arrayFind() with the string you want to find and the array you want to search in.
function arrayFind(needle,haystack) {
var matchList = [];
var regex = new RegExp(needle,'gi');
for(i in haystack) {
if(haystack[i].match(regex)) {
matchList[matchList.length] = haystack[i];
}
}
return matchList;
}If you didn’t need to use a variable for the regex you could eliminate that line and just use /searchterm/gi for a global case-insensitive search of the array. Since we are however, we need to make use of the RegExp object.