views:

193

answers:

2

hello,

I have a webservice

[Serializable]
    public class DataObject
    {
        public int ID { get; set; }
        public string Description { get; set; }
    }


    [WebMethod]
    public DataObject[] GetCities(string q, int limit)
    {
        // A collection to hold our results
        List<DataObject> customers = new List<DataObject>();

        // Our source of names, could be a DB query
        string[] db = new string[]{"aaa","bbb","ccc","ddd","ddsads","asdsad","asdsad","dsfsfd"};

        // Looping through the datasource to select the items that match
        int i=0;
        foreach(string cust in db)
        {

            if(cust.ToLower().StartsWith(q.ToLower()))
            {
                i++;
                customers.Add(new DataObject { Description = cust, ID = i });
            }
        }

        // Return the items that contained the text in alphabetical order
        return customers.ToArray();

    }

Javascript:

// and in my javascript I use jquery autocomplete like this 
$("#txtCity").autocomplete("Autocomplete.asmx/GetCities", { dataType: "xml", datakey: "Description", max: 5 });

the question is: how can I get in javascript the ID of the item selected in the autocomplete? I want to pass it to another function.

+2  A: 

You need to add a results handler:

$("#txtCity").autocomplete("<Your existing stuff here>").result(
         function(event, item, formatted)
         {
            // Use the item property
         }
      );
GenericTypeTea
which js do I need to make it work ? cause I get error "object doesnt support .... "10X
haddar
You need jquery.autocomplete.js and jquery.js.
GenericTypeTea
not working .... object doesnt support any idea why ?
haddar
I've updated the answer, try that.
GenericTypeTea
no still the same error ...but I tried to use : formatItem: function(data, i, max) { debugger; return data.Desc ; }, formatResult: function(data, data2) { //debugger; //alert(data) }and it works, but the data allwaya contains only the "Description" and not the "ID" ,could it be cause I'm calling autocomplete only with datakey: "Description" ?
haddar
Post your code up in your questions.
GenericTypeTea
A: 

i found what i needed in

http://stackoverflow.com/questions/927766/formatting-data-for-jquery-autocomplete-results

10X

and the event is "result" not "results" .... 10X man !!

haddar
Woops! Silly typo - fixed.
GenericTypeTea