Get selected object from jQuery Autocomplete
I'm using jQuery 1.8 Autocomplete.
Is there any way of getting the selected object outside of one of the event handlers?
I'm trying to do something like...
开发者_运维技巧 $("#searchUsers").autocomplete({
source: 'Users/List',
});
$("#addUser").click(function() {
// get the selected user Id
var item = $("#searchUsers").autocomplete('selected');
alert(item.Id);
});
I can't see any way of doing it but it seems a pretty obvious requirement.
I was running to the same problem. I could get access to the selected item as an object.
$("#searchUsers").data("autocomplete").selectedItem
The default behavior is that when the item is selected, the value is placed in the text box. So you could get it by just doing $("#searchUsers").val()
.
If you need more information from the selected item, then you need to pass a select
event handler, and within that handler, store the information elsewhere.
add the select
event to your autocomplete function:
search: function (event, ui) {
$("#searchUsers").val('');
},
select: function (event, ui) {
foo = ui.item.label;
$("#bar").val(ui.item.id);
baz = (ui.item.JsonField);
}
look at the Events tab here
edit:
added the search
event to the function. I'm using the search
event to clear fields/variables every time the user beings a search
Old question, but still...
Just define a JavaScript variable, and, in select event, set the object to that variable. For example:
$(function () {
var object_selected= -1;
$("#q").autocomplete({
source: "path/to/jsondata",
minLength: 3,
select: function (event, ui) { //This is the event that you need to implement
$('#q').val(ui.item.value);
object_selected = ui.item; //This is what you will use later.
return true;
}
});
});
精彩评论