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.
- Closing the autocomplete dropdown when clicking outside it – if you’re relatively new to JavaScript/ jQuery, you might not know a lot about event propagation. So you’d probably stop event propagation to close it, as suggested by the top-voted answer at this Stack Overflow question. But as others have commented there, this is a dangerous practice. The best method to do this is explained nicely by Philip Walton here.
- 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.