Archive for January, 2009

jScript AutoComplete and XML

Recently I’ve been getting really into using the jQuery library for all my javascript needs. When our project needed a way of populating a listbox, I turned to the AutoComplete plugin by Jörn Zaefferer. This plugin is pretty easy to use, and allows you to filter a javascript array using an input field, and displays the results as a nice list below the input. This seemed to be pretty ideal, but unfortunatly the documentation is rather sparse on a few key points. First of all, although the plugin accepts a URL, the documentation doesn’t tell you what to do if your URL is XML instead of the standard JSON.

After going through the code, I discovered an undocumented parse function, which allowed me to do exactly what I wanted. The XML that our CMS outputs is like this:

< ?xml version="1.0" encoding="utf-8"?>
<drivers>
 <driver id="439516">
  <name>Johnstone, Steve</name>
 </driver>
 <driver id="43423">
  <name>Johnstone, Bob</name>
 </driver>
</drivers>

And the code for the Parse function was:

$("#identifier").autocomplete(
    "http://www.yoururl.com/results.xml", {
        parse: function (data) {
            var parsed = [];
            $("Driver",data).each(function()
            {
                var row = [
                        $("Name", this).text(),
                        $(this).attr("id")
                    ];
                parsed[parsed.length] = {
                    data: row,
                    value: row[0],
                    result: row[0]
                };
            });
            return parsed;
        },
    }
);

Where, in the parsed array that you return, value: is the value that the data is being filtered on, result: is the value that is placed in the input box, and data: is an object that contains any additional information that you wish to get from the XML (in my case the ID of the Driver).

If you wish to use the additional data that you get back, then on the end of the plugin initilization add the following:

.result(function (event, item){
   // Your code goes here.
});

Where item is the array of data that you created in the parse function.

Tags: , , , ,

1 Comment



SetPageWidth