jQuery UI autocomplete as a kind of IntelliSense

I recently had to develop an email template system, where the user could create a new email template with a couple of placeholders to be replaced when the email is compiled and sent. What I wanted was a normal textarea where the user could type out the email body, but when they pressed the $ key followed by a couple of characters, then the jQuery UI dialog should dropdown and show the various fields that are available and match with the characters entered.

To start of, lets create a form with the email controls:

We can then add some styling:

We’ll also need script references to [jQuery][1], [jQuery UI][2] and [jQuery Caret Utilities by Gary Haran][3] and a reference to a jQuery UI stylesheet:

[1]: http://jquery.com
[2]: http://jqueryui.com
[3]: https://github.com/garyharan/jQuery-caret-utilities

Lets create a namespace to contain our variables, object literals and methods.

Next, we’ll create some test data.

Next we’ll set two variables, the first will be a flag to indicate when we’re requesting a “manipulated” search and the second will be the regular expression defining the search term we want.

Next we’ll setup the autocomplete plugin on our controls and define a couple of callbacks/overrides. Manipulating the **source** allows us to do a custom search, in this case we want to ignore the $ sign and only search with the term that follows it. We might also want to display a sorted list of matches. We’ll implement the **search** callback in order to ignore the normal behaviour of searching on every keypress, but only when we find a match near the caret for our my.reSearch regular expression will we call the search manually. We’ll also change the **select** behaviour, since we don’t want the entire contents of the input control to be replaced, but only the $ sign and the few characters following it. Finally we’ll ignore the **focus** event’s behaviour.

The code is also available on [jsfiddle.net][4] to play with.

[4]: http://jsfiddle.net/jacoswarts/ta2Lm/

Posted in Blog, Develop