Autosuggest in Spry

Autosuggest isn’t new to Spry 1.5, but I never had a chance to take a look at it till this morning. Surprisingly it wasn’t too difficult. Tonight’s example will be rather simple, but I’ll follow it up with a ColdFusion-based one tomorrow.

At the simplest level, to enable autosuggest you create a simple text field. This is obviously the field that will have the autosuggest tied to it. So I’ll start off with that:

<input type="text" name="search" />

Next I wrap the form field in a div:

<div id="mySuggest"> <input type="text" name="search" /> </div>

This is simply going to wrap our autosuggest area. So next lets talk data. Where will the autosuggest information come from? Luckily it comes from the datasets we know and love in Spry. So for this demo I’ll use the following:

<script> var dsCharacters = new Spry.Data.XMLDataSet("data.xml","people/person"); </script>

Now that I’ve got a DataSet, I can use it just like I’ve used Spry datasets before. So for example:

<div id="resultsDIV" spry:region="dsCharacters"> <span spry:repeat="dsCharacters" spry:suggest="{name}">{name}<br /></span> </div>

This shouldn’t look different from previous Spry examples. In this case the repeating of the dataset is used for the autosuggest. I can put whatever HTML I want in there. The value that will be used comes from the spry:suggest.

Basically - thats it! We do need some libraries and a bit of JavaScript. Currently three JavaScript libraries and one CSS file is required:

<link href="/spryjs/SpryAutoSuggest.css" rel="stylesheet" type="text/css" /> <script language="JavaScript" type="text/javascript" src="/spryjs/xpath.js"></script> <script language="JavaScript" type="text/javascript" src="/spryjs/SpryData.js"></script> <script language="JavaScript" type="text/javascript" src="/spryjs/SpryAutoSuggest.js"></script>

Lastly, after the div we add one line of JavaScript:

<script type="text/javascript"> var theSuggest = new Spry.Widget.AutoSuggest("mySuggest","resultsDIV", "dsCharacters","name", {hoverSuggestClass:'highlight'}); </script>

The first argument points to the great div that wraps the entire autosuggest area. The second argument points to the div that will draw out the suggestions. The third argument is the dataset. Next we tell Spry what field to search. After that we can pass a set of arguments. One of the most important ones is the hoverSuggestClass. Without it the autosuggest is a bit hard to read.

You can see a demo here: To see the autosuggest in action, try a few Star Wars names.

Raymond Camden's Picture

About Raymond Camden

Raymond is a developer advocate for Extend by Auth0. He focuses on serverless and enterprise cat demos. If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support.

Lafayette, LA