Category: web development

jQuery Autocomplete Using XML as Data Source

Update: fixed broken links to demo and zip.

Introduction

The following article will describe how to use an XML file as a Data Source for the jQuery Autocomplete plugin.

The jQuery Autocomplete Plugin documentation is lacking on examples, or details, on how to use an XML file as the data source. So this is my attempt to provide a simple example of how to use XML with the Autocomplete Plugin.

The plugin can take an array of strings, so we need to need to develop some code to read the XML file into memory and parse its contents into an array of strings. Once we have an array of strings, we can assign that array to the autocomplete plugin and attach that to a text field in our form. The following will step through that process.

Demo

First things first. Here is a link to the demo.

Example Code

Below is the full code used for this article.


<!DOCTYPE html>
<html>
  <head>
    <title>jQuery Autocomplete: XML as data source</title>
    <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.js"></script>

 <script>
 $(document).ready(function() {
 var myArr = [];

 $.ajax({
   type: "GET",
   url: "states.xml", // change to full path of file on server
   dataType: "xml",
   success: parseXml,
   complete: setupAC,
   failure: function(data) {
     alert("XML File could not be found");
   }
 });

 function parseXml(xml)
 {
   //find every query value
   $(xml).find("state").each(function()
   {
     myArr.push($(this).attr("label"));
   });
 }

 function setupAC() {
   $("input#searchBox").autocomplete({
   source: myArr,
   minLength: 1,
   select: function(event, ui) {
     $("input#searchBox").val(ui.item.value);
     $("#searchForm").submit();
   }
  });
 }
});
</script>
</head>

  <body style="font-size:62.5%;">

  <form name="search_form" id="searchForm" method="GET" action="search_results.html">
   <label for="searchBox">Keyword Search</label>
   <input type="text" id="searchBox" name="searchString" />

   <button name="searchKeyword" id="searchKeyword">Sumbit</button>
  </form>

  </body>
</html>

Continue reading