How to make spell-error-proof autocomplete text boxes

Hi Everyone,

I've seen lots of sites implement autocomplete functions in text boxes. I have noticed even fewer sites have autocomplete implementations as good as this though:

So, what exactly is wrong? Why should i have to spell a word exactly to use an autocomplete text box? What if i can't spell it? What if i spell civilize as civilise? Haa! Even the text editor I am writing this on says "civilise" is a mistake.

As developers, we want our users to be able find what they need when they use our autocomplete functionalities. However, most autocomplete implementations use a basic text comparison operator, Text.Contains ... How does this affect us?

Positively, for the most part. It's simple to implement and we can speed on to other development tasks.

Negatively, when our users are not sure how to spell the word or phrase they are looking for.

Don't believe me? Try booking a flight to Ouagadougou.

But Fear NOT code brothers, for Winter is here! A JavaScript prototype function to give your auto-completes that google-like, smart, Tony Stark's Jarvis' feel.

Text.looksLikeItContains returns the degree of correlation/likeness of two strings as a double between 0 and 1. So, instead of Text.Contains, we can use Text.looksLikeItContains during string comparisons. For instance,

var txt = "michael";  
console.log(txt.looksLikeItContains("mik"));  

The above code prints out 0.5050505050505051 to the console, which is the degree of correlation of "mik" to "michael".

So, if you've got a list of strings as the source data for your autocomplete, and the user types "hello", you could sort the list by the degree of correlation of each list item in descending order, and display the first n items as the autocomplete text.

Let's see how that would play in jQuery's autocomplete function.

var data = ["michael", "nerdhands", "chilas", "javascript", "csharp", "java", "python"];

function autoCompleteSort (data, term) {  
   return data.sort(function (a, b) { 
              return a.looksLikeItContains(term) < b.looksLikeItContains(term);
   });
}

jQuery("input.suggest-user").autocomplete({  
    source: function (request, response) {
        response(autoCompleteSort(data, request.term));
    },
    minLength: 3
});

Now, if the user types "mikel", the autocomplete boxes would return ["michael", "chilas", "python", ... ].

Entering "pyto" would see a return of ["python", "michael", "chilas", ... ].

Much better huh? You could even apply it to creating something like google's "Did you mean [correct word]?" functionality.

The full code can be found here.

Also, check out this jsFiddle.

Feel free to improve on the code, and follow me on twitter and instagram.

Cheers!

Show Comments