At the time of writing this article, Materialize CSS framework’s Autocomplete widget didn’t work properly with AJAX calls. So I gave it a go myself.
Ideally, the autocomplete widget should have the following features.
- AJAX calls must be made only after a certain minimum number of characters are entered.
- Requests must not be sent until the user stops typing into the box. This means setting a reasonable timeout to check end of typing.
- If a request is already on its way when the user enters more characters, the existing request must be cancelled before sending a new one.
- Clicking a result or outside the results list must close the list.
- Certain keys should not trigger AJAX calls.
- The results must be scrollable with arrow keys and selectable with Enter.
The code looks something like this. A few important things are explained below it.
You can remove the timeout or escape fewer keys if you want. I used GSMArena’s search function to make a working demo, which you can test here. Note that you need to enable loading scripts from unauthenticated sources, so better try it with Chrome . Even with Chrome you need to allow loading such scripts with a teeny tiny notification that appears at the end of the address bar. The demo has images and the results link to other pages. Open the developer tools in your browser and notice how requests get cancelled if you type with small intervals. Try scrolling through the results with arrow keys. You probably don’t need to add an image to the list item or link it to another page. The idea is that you can, if you want to.
The code is pretty much self-explanatory, but let me point out a few important things.
- I’m getting all the results from the AJAX call and appending them to a single, long string, and then appending that string to the autocomplete dropdown in one go as a single jQuery object. This is more efficient than appending each result individually, taking full advantage of the ability of jQuery to insert a chunk of html in a string. This article has a great analysis of jQuery append() method to explain why I did this.
- Control keys such as Shift, Ctrl, Alt etc. are escaped conditionally. The conditional check uses the or operator for this, which kind of makes it long. Better alternative approaches are more than welcome.
Please suggest if you have any improvements to this code.
Until next time, then.