JQuery UI Autocomplete

I need 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 get 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 Canyen", "zzz": "69"}, {"name": "97355 Macouria Tonate", "zzz": "449"}])

Everything works very well, but I do not know how to get the "zzz" value for the selected item.

I tried

 alert(ui.item.zzz); 

But that will not work.

+4
source share
3 answers

An autocomplete widget expects a data source in array format using:

  • Objects that contain the label property, the value property , or both
  • Simple String Values

You are currently creating a second (array of string values) that works fine, but you can also slightly customize your data when you iterate over it, and also supply other properties of 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 that you supply the widget contains objects with the name property, you must get the autocomplete functionality and also access the zzz property.

Here is a working example (without calling AJAX): http://jsfiddle.net/LY42X/

+5
source

The source function is just filling in the name. If you want everything to be from this data structure, do the following:

 $("#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); } });​ 
0
source

It seems to be an array of objects ... what might be missing is "[0]" or generally "[index]".

Please check this: jqueryui.com/demos/autocomplete/#event-select

0
source

Source: https://habr.com/ru/post/1412672/


All Articles