JQuery autocomplete - How to handle additional data?

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

  Username1 | UserId1
 Username2 | UserId2

So, if I start typing "U", a list of "Username1" and "Username2" will appear, as expected. I could select the first element and the <input> value will become "Username1" , but what I really want to send to the server is the user ID.

Is there any way to keep the identifier that follows the username? I intend to make a form message about changing a text field. Maybe I'm too blind to see it in the docs or find it on Google?

+6
javascript jquery autocomplete
source share
3 answers

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

 $("#my_field").autocomplete(...).result(function(event, data, formatted) { if (data) { $("#the_id").attr("value", data[1]); } }); 
+6
source share

I was going to list a few methods here, but all but one are junk. Do the string-> user conversion on the server in the same way as you did to create a list for autocomplete.

Be sure to save autocomplete and perform an AJAX check, but if you try to smuggle important form data (like this) in the form through JS, at some point something will go wrong.

Also, if you need to handle user agents other than js, you will need to write this method in some way.

0
source share

FYI, this article http://vivien-chevallier.com/Articles/use-bing-maps-rest-services-with-jquery-to-build-an-autocomplete-box-and-find-a-location-dynamically has a good way to do this is through the author function 'displaySelectedItem', which is called through the jQuery 'select' autocomplete event (see article for full code).

Greetings

Matt

0
source share

All Articles