最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery autocomplete - How to handle extra data? - Stack Overflow

programmeradmin4浏览0评论

I'm struggling with the following problem. I use the jQuery autoplete 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 bee "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?

I'm struggling with the following problem. I use the jQuery autoplete 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 bee "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?

Share Improve this question asked Dec 16, 2008 at 19:42 TomalakTomalak 338k68 gold badges546 silver badges635 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 6

Use the result method of the autoplete 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").autoplete(...).result(function(event, data, formatted) {
    if (data) {
        $("#the_id").attr("value", data[1]);
    }
});

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-plete.

By all means keep the auto-plete 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.

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

Cheers

Matt

发布评论

评论列表(0)

  1. 暂无评论