How to do autocomplete JqueryUi with PHP return multiple data?

7

I have two inputs , I'm using automplete in only one. The autocomplete code:

$(document).ready(function() {
$.getJSON('include/funcoes/carrega_cidades.php', function(data){
var dados = [];

        $(data).each(function(key, value) {
            dados.push(value.name);
        });

        $('#cidade').autocomplete({ source: dados, minLength: 3});
    });
});

cidade is the input that has autocomplete and is returning normally. I need to bring in another input id_cidade , the city ID returned in autocomplete.

SQL:

    $pdo = new PDO("mysql:host=localhost; dbname=iboard; charset=utf8;", "root", "");
$dados = $pdo->prepare("

        SELECT
            id,name
        FROM
            cidade

    ");
$dados->execute();
echo json_encode($dados->fetchAll(PDO::FETCH_ASSOC));

How can I do this?

    
asked by anonymous 11.12.2015 / 20:32

2 answers

3

Simple, in jQuery UI, for you to have the value searched in the database being displayed in the list generated by autocomplete, you do not always have to use an array of string, but you can use an array of objects, since it has the attribute label as the desired value for display in the list generated by autocomplete.

For example:

 ['wallace', 'rray', 'bigown']

Can be used as:

[{label: 'wallace', id: 1}, {label: 'rray', id: 2}]

So you can access other attributes through ui.item .

Example:

$.getJSON('include/funcoes/carrega_cidades.php', function(data){

    var dados = [];

        $(data).each(function(key, value) {
            dados.push({label: value.name, id: value.id});
        });

        $('#cidade').autocomplete({ 
            source: dados,
            minLength: 3,
            select: function (event, ui) {
                  if (ui.item && ui.item.id) {
                     $("#cidadeID").val(ui.item.id);
                  return false;
               }
           },

        });
    });
});
    
05.01.2016 / 15:13
0
  • Instead of taking the data just for the name of the city, place the object of the city in the vector.
  • Aim this vector as source of data
  • Include a method that will be called when choosing an item
  • Overload the autocomplete rendering function by telling it that you want to display the object's field
  • It will look like this:

    $.getJSON('include/funcoes/carrega_cidades.php', function(data){
        var dados = data;
        $('#cidade').autocomplete({ source: dados, minLength: 3,
           select: function (event, ui) {
                if (ui.item && ui.item.id){
                     $("#cidadeID").val(ui.item.id);
                     return false;
                }
           }
        }).autocomplete( "instance" )._renderItem = function( ul, item ) {
          return $("<li>").append(item.name).appendTo(ul);
        };
    });
    

    Reference: JQUERY UI Doc's

        
    04.01.2016 / 20:00