I am trying to pull some data off a json and display them using jquery autocomplete.
The json array contains ID, Title, Date. On the display, I want to show the Title and Date and on click i want to parse the specific ID for that title.
So currently I have:
$("input").autocomplete({
source: function (d, e) {
$.ajax({
type: 'GET',
url: url + mode + encodeURIComponent(d.term) + key,
dataType: "jsonp",
success: function (b) {
var c = [];
$.each(b.results, function (i, a, k) {
c.push(a.title + " " + a.date) // Displays Title and Date
});
e(c)
}
})
},
select: function (a, b) {
console.log(b);
// Appends an array with 2 keys: Value and Label.
// Both display the title and date as shown above.
}
}).data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a>"+ item.label + "</a>" )
// Here I want to append a.id as class of this
// but the only values are value and label.
.appendTo( ul );
};
So how can I append <li class="' + a.id + '">" + a.title + " " + a.date + "</li>"
You're stripping out the extra properties with your $.each
loop inside of the AJAX success function (as a sidenote, I'm pretty sure $.each
's callback does not take a third parameter). Just append a label
property to each result item and it should work fine:
source: function (d, e) {
$.ajax({
type: 'GET',
url: url + mode + encodeURIComponent(d.term) + key,
dataType: "jsonp",
success: function (b) {
var c = [];
$.each(b.results, function (i, a) {
a.label = a.title + " " + a.date;
c.push(a);
});
e(c);
}
})
},
The widget will work fine with extra properties, you just must have at least a label
or value
property.
Now in your _renderItem
function, you can access the title
and date
property of each item:
.data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a>"+ item.label + "</a>" )
.addClass(a.id) // <---
.appendTo( ul );
};
Try this. Place the ID in the value of your ajax call.
$( "input" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: url + mode + encodeURIComponent(d.term) + key,,
dataType: "jsonp",
success: function( data ) {
response( $.map( data, function( item ) {
return {
label: item.title ", " + item.date,
value: item.id
}
}));
}
});
}
}).data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<li "+ "class="+"item.value + ">"item.label + "</li>" )
.appendTo( ul );
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With