views:

26

answers:

1

I have an XML file dynamically created from a database where each item has both an id and name. In the following syntax:

<item>
   <id>1</id>
   <name>FirstName</name>
</item>

... and so on ...

I am trying to use these values for a jQuery autocomplete, where the ID will be submitted via form when the name is selected from the autocomplete.

I've tried the following block of code (executed from a button within a form):

function listItems(){
    var dataString = "";
    dataString += $("form#getItemsForm").serialize(); 

    $.ajax({ type: 'GET', url: 'myXML.xml', dataType: 'xml', success: function(xml){
        var myList = new Array();
        $('restaurant', xml).each(function() {
            var myId = Number($(this).find('id').text());
            var myName = $(this).find('name').text();
            myList[myId] = myName;  
        });
        alert(myList);
        $('.listItems').autocomplete({source:myList});
    }});
}

However, this is not working as the IDs begin at 1 and the array is searching for an index of zero so when I alert myList it popups with ,FirstName,SecondName (instead of FirstName,SecondName -- no leading comma).

I've tried making an array of objects but that's a little more cryptic to me as my alert returns [object Object] for each item.

Any pointers would be helpful. Thanks!

A: 

If you want the name attribute to appear as the 'label' of the item and the id to be the 'value', you could do this:

var myList = [];
$('restaurant', xml).each(function() {
    var myId = Number($(this).find('id').text());
    var myName = $(this).find('name').text();
    myList.push({label: myName, value: myId});  
});

Relevant excerpt from the documentation:

The local data can be a simple Array of Strings, or it contains Objects for each item in the array, with either a label or value property or both. The label property is displayed in the suggestion menu. The value will be inserted into the input element after the user selected something from the menu. If just one property is specified, it will be used for both, eg. if you provide only value-properties, the value will also be used as the label.

karim79
Hmmm, quoting seems to be broken in Chrome. Can anyone else confirm this?
karim79
Excellent. This is certainly a starting point to where I need to go. Thank you!
ladydev