How to make Jqueryui autocomplete with PHP return multiple data?

Asked

Viewed 1,595 times

7

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

$(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 who has the autocomplete and is returning normally. I need to bring it to another input the id_cidade, 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 that?

2 answers

3


Simple, in jQuery UI, for you to have the value searched in the database displayed in the list generated by the autocomplete, you do not need to always use a string array, 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 the autocomplete.

For example:

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

Can be used as:

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

Therefore, you can access other attributes through the 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;
               }
           },

        });
    });
});

0

  1. Instead of taking the data only of the name of the city, put in the vector the object of the city.
  2. Point to this vector as source of data
  3. Include a method that will be called when choosing an item
  4. About load the autocomplete rendering function telling him that Voce wants to display the "name" field of the object

Will stay 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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.