Autocomplete in Umbraco 4.5 using jQuery

I was searching too much, and never found something fast and useful. So I had to implmenet, using jQuery and the new Umbraco 4.5 a frontend feature everyone calls “AutoComplete”.

Here it is my implementation; of course it could be faster and optimized, but this solution works pretty nice with the website i was working on.

First of all, we need jQuery on our website, I’m using the 1.4.2 version today. Next, we need the jQuery UI plugin downloadable from here (remember the dependencies if you choose custom download).

When we could have this (I choosed the custom download) in our head tag:

<script type="text/javascript" src="/scripts/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="/scripts/jquery-ui-1.8.2.custom.min.js"></script>

we can go on.

Next step is to create the remote datasource for autocomplete. I suppose we needs to “autocomplete” only one of our document-types called ExampleDoc, ad I also suppose we have ad homepage tree node using ExampleHome as a document-type.

If you don’t use, we should create a node “Services” in our content tree. This node will contains services nodes will be never shown in menus or in website, but we use it for other purposes, like this example.

As a child of Services we create a node called “AutoComplete”. In the template (masterpage) corresponding to the document-type, we will add a Umbraco Macro referencing a new xslt file, we should AutoComplete.xslt.

The output I’m expecting is a json serialized object will be deserialized  by jQuery UI plugin we download before.

So i work in this way:

<xsl:template match="/">
  [
  <xsl:for-each select="$currentPage/ancestor-or-self::ExampleHome/descendant::ExampleDoc[@isDoc and starts-with(my:ToUpper(./@nodeName), my:ToUpper(my:QueryString('term','')))]">

    { "id": "<xsl:value-of select="./@nodeName"/>",
    "label": "<xsl:value-of select="./@nodeName"/>",
    "value": "<xsl:value-of select="./@nodeName"/>" }
    <xsl:if test="position()!=last()">
      ,
    </xsl:if>
  </xsl:for-each>
  ]
</xsl:template>

You can clearly see I use two custom functions (Xslt Extension): ToUpper and QueryString. Here it is a post shows how to create and use these methods in xslt files.

Now, we just need to add this script to our page contains the search text-box:

$(function () {
  $("input#searchText").autocomplete({
    source: "/services/autocomplete.aspx",
    minLength: 2
  });
});

where /services/autocomplete.aspx is the page corresponding to the page contains the macro just created.

Leave a Reply

*