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:

XHTML

1

2

3

4

5

6

7

8

9

10

11

12

13

14

<html>

<head>

</head>

<body>

<form>

<label for="toInput">To</label>

<input type="text"id="toInput" />

<label for="subjectInput">Subject</label>

<input type="text"id="subjectInput" />

<label for="bodyTextarea">Message Body</label>

<textarea type="text"id="bodyTextarea" ></textarea>

</form>

</body>

</html>​

We can then add some styling:

CSS

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

form{

color:#555;

font-family:Impact,Charcoal,sans-serif;

width:30em;

margin:3em;

}

label {

display:block;

}

textarea {

width:100%;

height:10em;

}

input {

width:100%

}

textarea, input {

color:#333;

font-family:‘TrebuchetMS’,Helvetica,sans-serif;

padding:0.5em;

}

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:

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.

JavaScript

1

2

3

4

//a flag to indicate when we called the search manually

my.manualSearch=false;

//the regular expression used to determine the search string, a $ sign followed by 0-10 characters, followed by the end of input

my.reSearch=/$[^$]{0,10}$/i;

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.