I need some help with the code below.
$("#auto_cp").autocomplete({
minLength: 3,
//source
source: function(req, add) {
$.getJSON("friends.php?callback=?", req, function(data) {
var suggestions = [];
$.each(data, function(i, val) {
suggestions.push(val.name);
});
add(suggestions);
});
},
//select
select: function(e, ui) {
alert(ui.item.value);
}
});
using FireBug, i'm getting this in my console :
jQuery171003666625335785867_1337116004522([{"name":"97300 Cayenne","zzz":"203"},{"name":"97311 Roura","zzz":"201"},{"name":"97312 Saint Elie","zzz":"388"},{"name":"97320 Saint Laurent du Maroni","zzz":"391"},{"name":"97351 Matoury","zzz":"52"},{"name":"97354 Remire MontJoly Cayenne","zzz":"69"},{"name":"97355 Macouria Tonate","zzz":"449"}])
Everything is working very fine, but I don't know how to get the value of 'zzz' on select item.
I tried
alert(ui.item.zzz);
But it doesn't work.
The autocomplete widget expects a data source in array format with either:
You are currently building up the second (an array of string values), which works fine, but you can also slightly tweak your data as you iterate over it and also supply the other properties in the object:
$("#auto_cp").autocomplete({
minLength: 3,
//source
source: function(req, add) {
$.getJSON("friends.php?callback=?", req, function(data) {
var suggestions = [];
$.each(data, function(i, val) {
suggestions.push({
label: val.name,
zzz: val.zzz
});
});
add(suggestions);
});
},
//select
select: function(e, ui) {
alert(ui.item.zzz);
}
});
Now, since the array you're supplying the widget contains objects with a name property, you should get autocomplete functionality and also gain access to the zzz
property.
Here's a working example (without the AJAX call): http://jsfiddle.net/LY42X/
You're source function is only populating the name. If you want everything from that data structure, do this:
$("#auto_cp").autocomplete({
minLength: 3,
//source
source: function(req, add) {
$.getJSON("friends.php?callback=?", req, function(data) {
var suggestions = [];
$.each(data, function(i, val) {
suggestions.push(val); //not val.name
});
add(suggestions);
});
},
//select
select: function(e, ui) {
alert(ui.item.value.zzz);
}
});
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