I have the current function which uses AJAX. It retrieves a JSON list of objects correctly. Each object has an ID & a Name. I'm unsure how to map each object ID to the Value and each name to the Label so that when a user chooses an option, I can actually process the selection.
$(function() {
var nameArray = [];
$("#search").autoplete({
source : function(request, response) {
$.ajax({
url : "controller",
type : "GET",
data : {
term : request.term
},
dataType : "json",
success : function(data) {
$.each(data,function(key,val){
nameArray.push(val.Name);
});
response(nameArray);
}
});
}
});
At the moment I just read the names in to an array and send that through the response to be used in the JQuery-UI autoplete. However I need a way to send both val.Name & val.ID.
This is so that I can later use 'ui.item.label' and 'ui.item.value' within a select:function.
Thanks
I have the current function which uses AJAX. It retrieves a JSON list of objects correctly. Each object has an ID & a Name. I'm unsure how to map each object ID to the Value and each name to the Label so that when a user chooses an option, I can actually process the selection.
$(function() {
var nameArray = [];
$("#search").autoplete({
source : function(request, response) {
$.ajax({
url : "controller",
type : "GET",
data : {
term : request.term
},
dataType : "json",
success : function(data) {
$.each(data,function(key,val){
nameArray.push(val.Name);
});
response(nameArray);
}
});
}
});
At the moment I just read the names in to an array and send that through the response to be used in the JQuery-UI autoplete. However I need a way to send both val.Name & val.ID.
This is so that I can later use 'ui.item.label' and 'ui.item.value' within a select:function.
Thanks
Share Improve this question edited Jan 27, 2016 at 17:37 Kyanite asked Jan 27, 2016 at 17:08 KyaniteKyanite 7563 gold badges15 silver badges30 bronze badges 02 Answers
Reset to default 4You need to push an object to the array that has the properties you want.
success : function(data) {
var nameArray = [];
$.each(data,function(key,val){
nameArray.push({value:val.Name, label:val.Name, id: val.id});
});
response(nameArray);
}
You could also simplify this a little bit using Array.prototype.map()
var nameArray = data.map(function(item){
return {value: item.Name, label: item.Name, id: item.id};
});
Use
JSON.parse(data)
inside your success function to parse the results into an object. From there you'll access its attributes as you would on any object.