Skip to content

Instantly share code, notes, and snippets.

@sharif2008
Last active June 26, 2016 10:15
Show Gist options
  • Save sharif2008/5302b2b6a529b4b54d53312e30bccfbe to your computer and use it in GitHub Desktop.
Save sharif2008/5302b2b6a529b4b54d53312e30bccfbe to your computer and use it in GitHub Desktop.
JQuery Auto-Complete on Complex Javascript Object/JSON
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<input id="name" type="text"/>
<input id="email" type="text"/>
$(function() {
var users = [{
"email": "[email protected]",
"name": "marie"
}, {
"email": "[email protected]",
"name": "miss"
}];
function handleAutocomplete(term) {
// use 'term' for custom filtering etc.
var options = $.grep(users, function(e) {
return e.name.startsWith(term);
});
return options;
}
$("#name").autocomplete({
minLength: 0,
source: function(request, response) {
var name = request.term;
var data = handleAutocomplete(name); /* get answers from somewhere.. */
response(data);
},
focus: function(event, ui) {
$("#name").val(ui.item.name);
return false;
},
select: function(event, ui) {
$("#name").val(ui.item.name);
$("#email").html(ui.item.email);
return false;
}
}).autocomplete("instance")._renderItem = function(ul, item) {
return $("<li>")
.append("<a>" + item.name + "<br>" + item.email + "</a>")
.appendTo(ul);
};
});
@sharif2008
Copy link
Author

Have a look on live https://jsfiddle.net/duoc5bbh/1/

@sharif2008
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment