Adding metadata to jQuery UI autocomplete
I'm writing a messaging application that uses jQuery UI autocomplete in the "send" field. I have it all working fine, but I need to attach bits of metadata, like a user id, to the items.
When the item is selected, I plan on adding a 开发者_如何学运维hidden input with the user id, like so: <input type="hidden" name="to[]" value="4" />
Adding one for each user selected. Then when the form is submitted, this data will be sent through to a php script, where I can send messages to each user.
I'm just wondering if anything like this is possible, if not, what might be the best way to get around it? Or, is there a better way of doing it than what I'm thinking?
Thanks,
You are on the right track!
The autocomplete widget is built to handle situations like this. As long as items in your source
have a value
property (and optionally a label
property), the widget will render the options correctly.
So you have two options. You can provide the label
and value
property and create your hidden input
elements with the value
property upon the select
event, or use your own attribute. It's easier to see with an example:
var users = [
{ label: 'Jon', value: 1 },
{ label: 'Jeff', value: 2 },
{ label: 'Marc', value: 3 },
{ label: 'Josh', value: 4 },
{ label: 'Andrew', value: 5}
];
$("#autocomplete").autocomplete({
source: users,
select: function(event, ui) {
$("body").append("<input type='text' value='" + ui.item.value + "'/>");
}
});
Here's a working example: http://jsfiddle.net/EYQLV/1/
You could just as easily use ui.item.id
if each item in your source contained that property.
精彩评论