Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery autocomplete - How to handle extra data?

I'm struggling with the following problem. I use the jQuery autocomplete plugin to get a list of suggested values from the server. The list would look like this:

Username1|UserId1
Username2|UserId2

So if I start typing "U", a list of "Username1" and "Username2" pops up, as expected. I could chose the first item and the <input>'s value would become "Username1", but what I really want to send to the server is the user ID.

Can I somehow get a hold of the ID that is following the user name? I intend to do the form post on change of the text box. Maybe I'm just too blind to see it in the docs or to find it on Google?

like image 329
Tomalak Avatar asked Dec 16 '08 19:12

Tomalak


1 Answers

Use the result method of the autocomplete plugin to handle this. The data is passed as an array to the callback and you just need to save data[1] somewhere. Something like this:

$("#my_field").autocomplete(...).result(function(event, data, formatted) {
    if (data) {
        $("#the_id").attr("value", data[1]);
    }
});
like image 71
davidavr Avatar answered Oct 17 '22 04:10

davidavr