I have an input field (text) that I want to perform autocomplete on with multiple names. It acts like the To: field in Gmail, with the user typing in a name and hitting enter and continuing. The problem is that I have a list of names and that's what gets added to the input field and once you submit, as far as I know, only the field string gets sent to the server. The problem is when there are two people with the same name, so: John Smith, Bob, John Smith
might be inputted and that string will get sent to the server.
On t开发者_高级运维he backend, all users have a unique id. Is there any way I can have the users' names be the autocomplete source but have their ids sent to the server?
I'm using jQuery 1.5.1 and this plugin: jQuery UI Autocomplete
The standard search will offer up everything you need. You just need to use a $.map()
function to get the data you need out from the server response. Example:
...
success: function (data) {
response($.map(data.d, function (item) {
return {
id: item.ContactId,
value: item.LastName + ", " + item.FirstName
}
}))
}
...
Then just store the selected items (including the ids and names) in a $().data()
variable on the input. Example:
...
select: function (event, ui) {
$(this).data("Selected", item);
}
...
Now when you're ready to post your value back to the server, you can simply send the id of the selected entry like so:
var idToSend = $("#autoComplete").data("Selected").id;
I hope that helps. Good luck!
* * EDIT * *
Sorry, the $.map()
was a split thought. The data.d
in my example is .NET specific, but there are two properties that are native to the Autocomplete plugin (.value
and .label
).
.value
will be what is shown and stored if .label
does not exist; otherwise, .value
will be treated as the value stored in the input post-selection, and .label
will be what is displayed in the dropdown.
Use the select event in Jquery UI autocomplete to trigger javascript that will store the IDs you need in a hidden field in the same form. See the documentation for the select event here:
http://jqueryui.com/demos/autocomplete/#event-select
精彩评论