- 8 min read

jQuery Autocomplete Using XML as Data Source

Update (11/30/2012): added a new demo that only searching the beginning terms of the autocomplete source.

Update: added a new demo for autocomplete for two fields in a form.

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 develop 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.

Two fields in a form that have autocomplete functionality. Demo 2

This demo only searches the beginning terms of the source provided. Demo 3

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>

jQuery Library Includes

The following libraries and css are used for this example:

XML File

The XML file used for this example is very basic. It consists of a parent element labeled states and child elements labeled state for each item that can be suggested as a search option.

<?xml version="1.0" encoding="UTF-8"?>
<states>
 <state label="Alabama" value="AL" country="US" />
 <state label="Alaska" value="AK" country="US" />
 <state label="Arkansas" value="AR" country="US" />
 <state label="Arizona" value="AZ" country="US" />
 <state label="California" value="CA" country="US" />
 <state label="Colorado" value="CO" country="US" />
 <state label="Connecticut" value="CT" country="US" />
...

The Form

The following is the form used in this example:


<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>

Important features of the form

  • The form has an id of searchForm. This will be used later to submit the form when selecting a result in the search suggestion list.
  • Text Input field has an id of searchBox. This will be used to add autocomplete functionality to this form field.

Open XML file for parsing

In order for the form to display suggested search options, the XML file needs to be opened and parsed into memory. To do this, an ajax call is needed once the HTML document is ready.

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

Explanation

  • If XML file is loaded succesfully, parseXML function is called. Which will, as you guessed, parse the XML file into an array of strings.
  • Once the ajax request is completed, assign the autocomplete plugin to the searchBox field via the setupAC function.
  • If the ajax call fails to find the XML file, an alert prompt will display; notifying you that the file cannot be found. This method works great for an example, but a more elegant error method should be developed for a production version.

Note: be sure to change the url variable to the full path of file on your sever.

Parse XML

The following code will parse the XML opened through the ajax call above.

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

This function finds all elements named state and adds the label attribute of that element to the myArr variable, which is of type Array.

Once this function is complete, myArr will be populated with possible search suggestion strings.

Adding Autocomplete Functionality

In order to add autocomplete functionality, we need to add the jQuery plugin features to an input text field.

After the ajax call is complete, the setupAC function is then called which will configure the autocomplete feature.


function setupAC() {
 $("input#searchBox").autocomplete({
     source: myArr,
     minLength: 3,
     select: function(event, ui) {
       $("input#searchBox").val(ui.item.value);
       $("#searchForm").submit();
     }
 });
}

Explanation

  • source: myArr assigns the array of strings parsed from our XML file as the data source
  • A minimum of 3 characters must be entered before suggested search options will display (minLength value). This can be changed to work for your solution.
  • The select option will replace the text in the input field with the search suggestion selected item. This is needed so that the form will submit with the search term within the form properties. Otherwise, the form would submit with a blank searchBox value if a selection is made from the search suggestion dropdown.
  • Lastly, $("#searchForm").submit() submits the form.

Limitations

One major limitation I’ve found with this plugin is the option to limit the suggestion menu result set. For example, it would be great to have the option to display a maximum of 10 suggestions matching the user’s search criteria. This example doesn’t have this problem, but imagine if your data source had thousands of strings and more than 50 of them had the characters “add” somewhere in the string. The suggestion dropdown would be too long to see all those results on the screen without scrolling.

Modifications to Autocomplete Functionality

jeffrey from the comment thread asked if there is a way to modify the autocomplete function to only search the first character of the state names.

Yes, this is possible. The see this in action, please check out the link for Demo 3.

We need to modify the way the source attribute is delcared to run a regex function on the myArr list to only select terms that match the beginning terms of each item. See below on how to modify the existing setupAC function (lines 3-8):

function setupAC() {
    $("input#searchBox").autocomplete({
        source: function( request, response ) {
	        var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( request.term ), "i" );
	        response( $.grep( myArr, function( item ){
	            return matcher.test( item );
	        }) );
	    },
	    minLength: 1,
	    select: function(event, ui) {
	        $("input#searchBox").val(ui.item.value);
	        $("#searchForm").submit();
	    }
    });
}

I can’t take all the credit for this code. I found a nice example on the jQuery UI API Documentation for the autocomplete widget website (see example 2).

Download Example

Here is a zip file containing all example files for this article. Feel free to reuse for your needs

I welcome comments or suggestions. All code is free to use as you see fit. No licensing here.

89 comments

  1. Scott

    Ryan, first, let me say this is great and your responsiveness to all these comments is amazing. I am trying to implement this inside an EditItemTemplate, but I can’t quite figure it out.

    Inside your script, I’ve tried replacing $(“input#searchBox”) with a document.GetElementByID findcontrol, but no luck. Any suggestions?

    • Scott

      Update: I changed the line for finding the searchBox to

      $(‘#’).autocomplete({

      but that’s giving me a datatype error between varchar and numeric. It seems like it’s finding the box. Here is the code inside the formview:

      Keyword Search
      <asp:TextBox ID="searchBox" runat="server" height="24px" width="320px" Text='’>

      Thanks for any ideas.

      • Scott

        Crud, my change isn’t showing correctly. I changed your line to the following (hopefully it’ll post this time),

        $ (‘ # ‘) .autocomplete({

      • Scott

        Not yet. I just didn’t want to keep adding to my thread. I was getting a null reference error so I moved the script into the the formview. The error went away, but the autocomplete is not doing anything. I’ve tried every combination of FindControl I could think of and still no joy. If I use the one I typically use, which I can’t enter here, I get a null ref error again. These FormViews cause me so much frustration. I’m not sure the convenience of what they do is worth it anymore.

  2. dvshubham

    Sir , could you please guide me ..can you suggest how to add different links for every label
    I mean if user searches for alaska or any other term it should go to google.com(any url we provide)

  3. Geg

    Hi John! Thanks to your tutorial I got my first autocomplete working! Thank you a lot for that!

    Now I would like to extend it a bit. According to your example: Is it possible to fill the ‘label’ attribute into the search box and automatically at the same time let the corresponding ‘value’ attribute be put into another (hidden) input field? I don’t know how to modificate the parseXml function and the setupAC function to do so. The idea then is to submit the ‘value’ attribute only.

    Thanks in advance! I almost went crazy searching for tutorials or examples.

    • Ryan

      @Geg,

      You can modify the parseXML function to push key/value pairs to the myArr array like this:


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

      Then change the setupAC function to add the selected value to a hidden input field with an id of “hiddenField”:


      function setupAC() {
      $("input#searchBox").autocomplete({
      source: myArr,
      minLength: 1,
      select: function(event, ui) {

      event.preventDefault();

      $("input#searchBox").val(ui.item.label);

      // add value to hidden field
      $("input#hiddenField").val(ui.item.value);
      $("#searchForm").submit();
      }
      });

      You would then need to add the corresponding hidden field to your form like this:


      input type="hidden" id="hiddenField"

      I hope that helps. Please let me know if you have any more questions. Happy coding!

      • Geg

        Yeehaw, it’s working! Thank you so much! I really have to learn more about the javascript syntax.

        But it is not over yet :) Now I am facing the problem that the function for searching the first character as shown in your Demo 3 is not responding anymore. I can understand why (I think the function does not know wether it should look for the value or the label items in the array) but again I had no luck in modifying your code to fit my needs. Of course I would like to look after the first character of the label items in the array.

        This is a question of syntax again, right? Would be great if you could helb me once more. I tried to find a hint at the W3 schools but my brain is not getting it.

        By the way people should learn a lesson from you how to deal with ‘stupid questions’ like mine. Most of the cracks would have suggested something helpful like ‘google it, dude!’. So thanks again!

        Geg

        • Ryan

          @Geg,

          Glad you got that working!

          Your current question took me a bit to figure out, but it turns out it’s a rather simple code change.

          in the setupAC function update


          return matcher.test( item );

          to this:


          return matcher.test( item.label );

          There aren’t any stupid questions. We are all learning. I know I still am.

          Please let me know if you have any more questions.

          Best of luck in your future endeavors, and happy coding!

          • Geg

            Almost forgot to say thanks again! Everything is working perfectly now. While playing with the code I never thought about changing the ‘return’ line. D’oh. Happy coding and living!

  4. Albert

    ups!! here it is:

    ·?xml version=”1.0″ encoding=”UTF-8″ standalone=”yes”?>
    ·response
    ·fidsData
    ·operatingAirlineName>KLMAmsterdamKL 1672On-TimeOn-TimeAmsterdam113:10
    ·fidsData>
    ·operatingAirlineName>KLM</operatingAirlineName….

  5. Albert

    Excellent tutorial. How can I parse xml code to get elements instead of attributes. I need to obtain flight and city from the following xml code:

    KLM
    Amsterdam
    KL 1672
    On-Time
    On-Time
    Amsterdam
    1
    13:10

    Thanks!

      • Albert

        Hi Ryan,
        This is the xml code example. I would need to extract flight and city. They both depend from // label. Besides since there might be more than one result for a single city, I need the results placed on a div, if this is feasible.

        /*

        KLM
        Amsterdam
        KL 1672
        On-Time
        On-Time
        Amsterdam
        1
        13:10

        …..
        ………….*/
        Thanks for your help.
        Albert

  6. Alex Gallegos

    Is there a hard limit on the number of records that can be in the XML file? I have this implemented on a sample page. If I cut the XML file down to a small sample size, this works great, but if I upload the full XML, it doesn’t do the lookup. My XML file has some 35,000 rows – I’m aware that this is a lot, but it’s a lookup of all the High Schools all across the country so I really can’t pare it down. The server doesn’t even attempt to show me the search results; I thought it’d be tolerable if it took a few seconds to finish, but it doesn’t seem to be doing anything – not hung, not an unresponsive script, just not even making an effort to try to do the lookup. I was hoping there was somewhere I could increase the timeout or the number of records to search against.

    Thanks!

    • johnstonianera

      That is a lot of data to parse, I\’m not surprised that the autocomplete plugin isn\’t working as expected. Also note that this plugin is fairly old, the newer version may be more responsive.

      Let me know if you haven\’t found a good solution. I\’d be happy to try and help further.

      Would it be possible to separate the files into high schools based on each state? Possibly force the user to select a state before they search for a high school…? That might result in a smaller xml files…

  7. Chris

    Hi, this is a great example – thank you. I’m trying to adapt it to use on our footwear website & I wondered if you could point me in the write direction.

    In the XML example snippet below (2,000 lines+), your ajax script works perfectly if someone types in “Black Smooth Leather” (ie 3 words in the right order), but I want it to show up if someone types “Black 8 Eye Boot” or “Airwair Classic Boot” or up to 5 words that match in any order

    I presume the text typed into the search box would need to be made into an array and the find function called for each word in the array, returning the results where each iteration is true

    Is this possible? I’ve managed to what I want working in a PHP script which parses an XML file but its too slow returning the results.

    Many thanks for any help you can advise on

  8. Oliver

    Hi! is it possible to combine :
    source: function( request, response ) {
    var matcher = new RegExp( “^” + $.ui.autocomplete.escapeRegex( request.term ), “i” );
    response( $.grep( myArr, function( item ){
    return matcher.test( item );
    }) );
    },

    and:

    source: myArr,

    so that when I begin to understand, it is the first words whose spelling begins typed letters. For example, if I want to take “washington”, typing “w”, I get rather:
    Washington
    West Virginia
    Wisconsin
    Wyoming
    Delaware
    Hawaii
    Iowa
    New Hampshire
    New Jersey
    New Mexico
    New York

  9. Leon

    Great example, but after the submission the only value submitted is “label”.
    I would also like to post “value” and “country”, and if possible as a hidden value.

    Can this be done, and if so how?
    Thank you for any info on this.

  10. tom

    hello man,the xml file is not loaded when i import the files into my local system. what can be the reason?

    • johnstonianera

      @tom,

      Make sure you are running the code in a LAMP/WAMP/MAMP environment. I don\’t think the javascript will work correctly unless you test on a local webserver. Your local machine will not know how to open the XML file. If that doesn\’t work, try testing the code on a live web server.

  11. Simon

    Hi! This is awesome. Is there any way to autocomplete “New York” even when someone write in “York New”?

    • johnstonianera

      @Simon,

      The autocomplete function should still display the \”New York\” option if the user starts typing in \”York\”. Since \”York\” is in the string of \”New York\”. I would hope the autocomplete functionality would give them a proper suggestion before the user finished entering \”York New\” because that would not be a match.

      I hope that helps.

    • johnstonianera

      @Dushan,

      That is odd. I tried the demos in Chrome Version 28.0.1500.71 (the latest build as of this comment) and the demos work fine. What isn\’t working on the demos for you? I\’d be happy to help if you can provide a little more information.

  12. pat

    Can this be modified to search multiple xml fields? something like this..

    BPS
    AFP to PDF AIX Transform (OEM CDP)
    AFP to PDF AIX Transform (OEM CDP)

    See where I’m going.. Maybe a better way exists in the framework?

    • johnstonianera

      @pat,

      Yes, I believe this is possible. You would need to add an additional xml.find function to grab an additional field and then concatenate that with the other query.

      Here is an example, assuming the xml file has a multiple state fields and multiple country fields.

      $(xml).find(\”state\”).each(function()

      {

      stateArr.push($(this).attr(\”label\”));

      });

      $(xml).find(\”country\”).each(function()

      {

      stateArr.push($(this).attr(\”label\”));

      });

      Please let me know if I can help with any other questions, or if I haven\’t answered your question.

  13. Ronald

    Great article, it’s been really helpful.

    I’m having a bit of a problem. I’m using the autocomplete for all the airport codes in the world, so it uses over 9000 items. It’s working, but it’s not showing the results for all of the airports in the xml file. Is there a limit I can set or anything else I can tweak in order to show all of the airports?

    *I changed the xml format to this:

    Thanks for your help

      • Ronald

        Sure, I’ll copy some bits of what I’m doing. My site is a wordpress site, so the JS is in the header.php file:

        $(document).ready(function() {

        var myArr = [];

        $.ajax({

        type: “GET”,

        url: “http://flywithacs.com/wp/wp-content/themes/ElegantFusion/includes/airports.xml”,

        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(“airport”).each(function()

        {

        var thisItem = $(this).attr(“code”) + ‘, ‘ + $(this).attr(“name”) + ‘, ‘ + $(this).attr(“city”) + ‘, ‘ + $(this).attr(“country”);

        myArr.push(thisItem);

        });

        }

        function setupAC() {

        $(“input#searchBox”).autocomplete({

        source: myArr,

        minLength: 3,

        select: function(event, ui) {

        }

        });

        }

        });

        There you can see the URL to the airports.xml file which has the list of 9000+ airports. I minified the file, son I can’t point out from which airport it stops showing the result. What I can tell you is that it only shows autocomplete values for airports in the USA, leaving out every other country. So I’m guessing it’s only working with less than the first 2000 values

  14. Mohankol

    I have implemented your code successfully. My query is that – How do we limit results(e.g:5) in jquery ui autocomplete? Earlier I tried with ‘slice’ function . But, it wasn’t working. Could you suggest me?
    I have used you query :
    source: function( request, response ) {
    var matcher = new RegExp( “^” + $.ui.autocomplete.escapeRegex( request.term ), “i” );
    response( $.grep( myArr, function( item ){
    return matcher.test( item );
    }) );
    },

    • johnstonianera

      @Mohankol,

      Try increasing the minLength variable to a value larger than 1. That will delay the autocomplete action until more than one character is matched in the search. That should help limit the amount of results that are displayed.

  15. Mahesh

    hi, very good articale.
    I am trying to down load the zip file but on click of that link nothing is displaying.
    pls provide me the full solution.

    Thanks in advance.

  16. Ramu

    hi I have created two xml files namely "states" and "cities" and the source code copied and assigned correct url then also i am not getting any thing.pls help me.

    • johnstonianera

      @Ramu,

      Sorry to hear you are having trouble. Unfortunately, I can't provide much help without seeing the code in question. Would you be able to put your code some place where I can take a closer look? I'd be happy to help once we are both able to see your working copy.

      Thank you

  17. mike

    I cant get the below to work. When I click the SUBMIT button, the results post to the iframe, but when I click the same value in the autosuggest drop down, it changes pages (and doesnt put the results in the iframe).

    please help. thank you, mike crl@crlnews.com

    <form name="input" id="searchForm" method="GET" action="http://www.crlaurence.com/apps/quickpricing/stock_table.aspx?product=&quot; >
    <label for="searchBox">Keyword Search</label>
    <input type="text" id="searchBox" name="product" formtarget="iFrameName"/>

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

    <iframe src="search_results.html" name="iFrameName" id="iFrameName" frameborder="0" width="800" height="600"/>
    </iframe>

    • johnstonianera

      @mike,

      Without seeing the full example of your code, I'll try to take a stab at your problem.

      From what you describe it sounds like once you select an item from the autosuggest dropdown, the form submits and takes you to a different page. To prevent that behavior, you will need to remove the line in your javascript code that automatically submits the form upon autosuggest selection.

      In my example, this would involve removing the "$("#searchForm").submit();" line in the setupAC function. This will make sure the user has to click the submit button on your form to invoke the form submit action.

      I hope that helps. Please let me know if I can be of any further assistance.

  18. jeffrey

    Hi, great tutorial!
    I was wondering..is there a way to modify the script to only search the first character of the state names?
    So if i type in AL, the suggestions will only show states that start with "AL" and not states with AL somewhere in the middle?

  19. johnstonianera

    @Jorge,

    Thank you for your comment! I'm glad the example and explanation were valuable to you.

    1) Please check the new demo I created. It demonstrates how to setup a form with two autocomplete text input fields. http://www.johnstonianera.com/demos/jQueryAutocom

    2) The example uses the jquery-us.css file to style the autocomplete dropdown. If you want to change the styles, I would recommend downloading that CSS file and modifying it to your needs. Make sure to reference that modified file in your CSS include.

    The CSS I used can be found here: http://ajax.googleapis.com/ajax/libs/jqueryui/1.8

    I hope that helps. Please let me know if you have any further questions.

  20. Jorge Eduardo

    Hi, very good explanation and example. Thanks, I have two questions:
    i) I need to let the user use the autocomplete in two different text fields in the same form, say one field for cities and second one for illness. How can I achieva that having in mind that must load two xml files, and initialize variables for each one.
    ii) How can I css format the drop menu that contains the matching labels?

    Thanks,

    Jorge eduardo

  21. Paul

    I used and modified this code and found it to be the easiest and most effective example I could find on the web – if reading this I would recommend using it, very good!

    The Limitation section describes limiting the number of items in the list – however I found a easy work around if you are getting very long drop down boxes. If anyone want to use it here is my "quick-fix"

    Create a CSS file and link it after the jquery-ui.css. In the new CSS you can override the .ui-widget class adn add in a max-height and overflow:hidden lie this

    .ui-widget {
    font-family: Arial,sans-serif;
    font-size: 14px;
    max-height: 426px;
    overflow: hidden;
    }

    Change the max-height to suit your needs

  22. wiyono

    Hallo,
    Nice one, thank you

    But how to make the result work?
    And not only "This page will contain search results…"
    Can you give me please simple sample?

    Thank you so much.

    • johnstonianera

      @wiyono,

      The demo sends a GET variable called searchString to the search_results.html page (search_results.html?searchString=Ohio).

      You could use this GET variable to do any processing you would need based on what the searchString variable contains (either from using the autocomplete functionality or entering text into the input box).

      For example, in PHP, you could access the GET variable like this: $_GET['searchString'].

      I hope that helps. Please let me know if yo have any further questions.

  23. anais

    Hi! Can you modify the code to make the matching start from the beginning? I've tried various solution but I couldn't make it work. I would love to see a working solution.

    • johnstonianera

      @anais,

      I'm not sure what you mean. I'm happy to help if you could elaborate on what functionality you would like to see.

      The demo shows the autocomplete matching start when one character is entered. Is that what you are looking for?

  24. Tom

    Thanks for tips on using XML sources, it is nice for newbies like myself. I am wondering about expanding the functionality so that when the visitor selects their state/province the code would populate both the state input and a separate country input..

    • johnstonianera

      @Tom,

      This is definitely possible with a little tweaking of the example code. Here is one way of populating two input fields based on the autocomplete selection:

      Step 1:
      Add an additional input field with id of "country" in your form.

      Step 2:
      Modify the parseXML function as found below:

      function parseXml(xml)
      {
      //find every query value
      $(xml).find("state").each(function()
      {
      var thisItem = {};
      thisItem['label'] = $(this).attr("label");
      thisItem['country'] = $(this).attr("country");
      myArr.push(thisItem);
      });
      }

      Step 3:
      Modify the setupAC function as found below:

      function setupAC() {
      $("input#searchBox").autocomplete({
      source: myArr,
      minLength: 1,
      select: function(event, ui) {
      $("input#searchBox").val(ui.item.label);
      $("input#country").val(ui.item.country);
      }
      });
      }

      I hope that helps. Best of luck on your jQuery endeavors!

      • Tom

        That worked like a charm. Thank you kindly.

        Now I need to see if I can use what I learned from your example and merge it with data from the geonames.org db, to create an autocompleter triggered off the city name, that would also subsequently fill in both the state and the country inputs.

  25. Jain

    Hi John, It works like a charm. But if I include the javascript in a separate file. It's not working.
    I put the code in the below file and call it from my jsp like this and it won't work. Do you have any idea ?
    <script type="text/javascript" src="js/pkval.js"></script>

    • johnstonianera

      @Jain,

      Without seeing your server setup or have knowledge of source code, my guess is that other javascript code is interferring or the path is wrong on the .js file you are trying to include.

      I hope that helps.

  26. Mak

    Hi John,
    Thank you so much for this wonderfully explained code.
    i have a question, it would be great if you could help me.
    On my page i have a table that uses an xml page. Artists and albums. When you click on the artist name an image on the right and side and some relevant content change according to the artist. I was wondering is there in a possibilities in being able to alter the code so it picks up my already functioning table. So if i type an artist in search box it will auto complete it and also i will be able to click and choose the artists which will then change the content on the page?

    • johnstonianera

      @Mak,

      Without seeing your code or an example, I can only speak hypothetically about how to get your functionality added to this autocomplete example.

      You should be able to add your function inside the setupAC function from the example above. If you add a hook to your existing code after line 37 from the demo, you should be able to leverage the functionality you've already built.

      For example:

      function setupAC() {
      $("input#searchBox").autocomplete({
      source: myArr,
      minLength: 1,
      select: function(event, ui) {
      $("input#searchBox").val(ui.item.value);
      // ADD YOUR FUNCTION HERE
      //$("#searchForm").submit(); &lt;- probably want to remove this line so that form does not submit
      }
      });
      }

      I would be happy to look into this further if you can provide an example…

      Thank you.

    • johnstonianera

      @Jung,

      I don't see an option to limit the number of results in the documentation.

      However, to paraphrase from the AutoComplete documentation; a possible solution might be to change the minLength value to something higher than one. This will increase the minimum number of characters a user has to type before the Autocomplete activates. Zero is useful for local data with just a few items. But the value should be increased when there are a lot of items, where a single character would match a few thousand items.

      I hope that helps.

  27. Harvey

    Great stuff… I've mangled everything to suit my own "Plans for World Domination" (admit it, we've all got one!)…
    But I've hit one teeny snag!

    How do I stop the "autocomplete" bit from submitting the form as soon as it's filled in (by selecting a result in the dropdown)?

    I've got a couple of other fields for people to enter, so I'd like them to have to press the "submit" button.

    • johnstonianera

      @Harvey,

      Looking at the demo provided, disabling the $(#searchForm").submit() line from the setupAC function should prevent the form submitting by selecting a result in the dropdown. To do this, remove or comment line 39 in index.html from the demo (download provided above).

      Here is an example:

      function setupAC() {
      $("input#searchBox").autocomplete({
      source: myArr,
      minLength: 1,
      select: function(event, ui) {
      $("input#searchBox").val(ui.item.value);
      // $("#searchForm").submit(); <—- this line submits the form when selecting a result from the dropdown
      }
      });

  28. Sol

    Hi

    Here's how I did it:

    All the labels show in the search box, but only Brand is populated on click through.

    `
    function parseXml(xml)
    {
    //find every query value
    $(xml).find("airport").each(function()
    {
    //you are going to create an array of objects
    var thisItem = {};
    thisItem['label'] = $(this).attr("label") + ' ' + $(this).attr("colour") + ', ' + $(this).attr("size") + ' (' + $(this).attr("brand")+ ') ';
    thisItem['value'] = $(this).attr("brand");
    myArr.push(thisItem);
    });
    }

    `

  29. Sol

    Hey, thanks so much for sharing this.

    How would I show the full details (as in option 1 in your last response), but actually use only the state to populate the form field ?

    Thanks
    Sol

    • johnstonianera

      @Sol.

      This can be accomplished by modifying the autocomplete function associated with the input searchBox inside of the setupAC function. Take the string (ui.item.value) sent into that function and split the string (for example: Alabama, AL, USA) into a new string variable. Then you can assign that new variable to the input#searchBox's value.

      Here is an example of the modified setupAC function, which places the full name of a state into the form field. Note: I've only tested this in Firefox.

      function setupAC() {
      $("input#searchBox").autocomplete({
      source: myArr,
      minLength: 1,
      select: function(event, ui) {
      var stateStr = ui.item.value.substring(0,ui.item.value.indexOf(',')); // adds the full state name to stateStr
      $("input#searchBox").val(stateStr); // substitute ui.item.value for stateStr
      $("#searchForm").submit();
      }
      });
      }
      });

      If you wanted to break out the string manipulation into multiple steps for more clarity you could do this:

      var wholeStr = ui.item.value;
      var stateStr = wholeStr.substring(0,wholeStr.indexOf(','));
      $("input#searchBox").val(ui.item.value);

      I hope that helps. Please let me know if you have any further questions.

  30. ryman

    hi
    first thank you for this nice explanation.I am very new to jquery and ajax i have small issue that is i want the XML to change based in user input.
    how can i changed the code so that everytime new xml is loaded from the server based on user input.
    What i am trying to do is everytime user inputs something asp file file will be called which will generate XML.
    How can i change the code to meet the requirements.
    thanks

  31. Homanp

    Great tutorial! Got it to work right away. Just have one question. How would you go about showing the autocomplete like: "Alabama, AL, USA".
    Would be awesome if you could give me a hint!

    • johnstonianera

      @Homanp.

      Option 1:

      You could modify the parseXML function that is included in the demo's index.html. This could be accomplished by combining the label, value, and country properties for each state xml element into one. Look at the "$(xml).find("state").each(function()" portion of the code.

      Here is an example:

      function parseXml(xml)
      {
      //find every query value
      $(xml).find("state").each(function()
      {
      // this variable combines the label, value, and country properties into a single string
      // which will be added to the search array.
      var thisItem = $(this).attr("label") + ', ' + $(this).attr("value") + ', ' + $(this).attr("country");
      myArr.push(thisItem);
      });
      }

      Option 2:

      If you don't want to mess with the JavaScript, you could modify the label (since the JavaScript is already adding this attribute to the jQuery search string) in the XML file for each state property.

      For example:

      <state label="Alabama, AL, US" />

      Change each state property in the XML file accordingly.

      I hope that helps. Please let me know if you have any further questions.

  32. zidar

    Thank you very much for this, it's a really nice explanation of everything. But the links, to the demo and .zip file, don't work. It would be really nice to have those two thing available too.

Leave a Reply