views:

1772

answers:

2

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?

A: 

I was going to list a few methods here but all but one is junk. Do the string->user conversion on the server as you've been doing to generate a list for the auto-complete.

By all means keep the auto-complete and do AJAX validation, but if you try and smuggle vital form data (like this) in the form via JS, something will go wrong at some point.

Besides, if you need to handle non-js user-agents, you'll need to write this method in any way.

Oli
This is not going to become a public application, so missing JS support is a non-issue. You would be right in general, though. In fact, I was working on the exact thing you propose but then thought that this can't be it. It just feels too ugly.
Tomalak
I can't see how it's ugly. The alternatives: adding extra form fields and setting them on auto-complete choice; or keeping the selected ID in JS and hacking it onto the end of the post data. Doing the look-up again is really the cleanest way...
Oli
+4  A: 

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]);
    }
});
davidavr
Beautiful, thank you. Other than reading the plugin source code, how would I have found that out? The docs don't mention it, AFAICS.
Tomalak
@Tomalak: It is in the docs. Look here: http://docs.jquery.com/Plugins/Autocomplete and scroll down to API Documentation and you'll see it.
davidavr
OK I must be blind then. Found it. I still think it is not really obvious, but at least I can say it's my bad. ;-) Thanks.
Tomalak