I\'m implementing a AJAX autocomplete/autosuggest feature, and not only do I want to do the usual show suggestions that are similar to what the user typed, but I\'d like to let
This specific type of autocompletion isn't supported in popular autocompletion plugins (for jQuery, Scripty...) because usually those provide a drop-down UI for choosing the wanted match.
So let's suppose we haven't got an out-of-the-box solution. Boo-ho. How hard can it be to code it up?
// takes a text field and an array of strings for autocompletion
function autocomplete(input, data) {
if (input.value.length == input.selectionStart && input.value.length == input.selectionEnd) {
var candidates = []
// filter data to find only strings that start with existing value
for (var i=0; i < data.length; i++) {
if (data[i].indexOf(input.value) == 0 && data[i].length > input.value.length)
candidates.push(data[i])
}
if (candidates.length > 0) {
// some candidates for autocompletion are found
if (candidates.length == 1) input.value = candidates[0]
else input.value = longestInCommon(candidates, input.value.length)
return true
}
}
return false
}
// finds the longest common substring in the given data set.
// takes an array of strings and a starting index
function longestInCommon(candidates, index) {
var i, ch, memo
do {
memo = null
for (i=0; i < candidates.length; i++) {
ch = candidates[i].charAt(index)
if (!ch) break
if (!memo) memo = ch
else if (ch != memo) break
}
} while (i == candidates.length && ++index)
return candidates[0].slice(0, index)
}
Test page here — it should work in normal browsers. For supporting IE use event listening from prototype.js, jQuery or other.