Handle autocomplete Jquery ui

1

I am implementing a query through an input system using the Jquery UI Autocomplete. In practice when querying a value by field name (Ex: Are) my input will display a list with possible returns (São Paulo, São Bernardo ...). This result is already possible in my script, however I need to manipulate the Id of the selected city. Since the name will only serve to view / select the user.

I have a php file that returns Json with the following columns of the table, id and nome .

In my Jquery script I already have a variable of type array in which I store the query data. I think my problem is here because I am not able to store it in a way that I can get id .

    $.getJSON('<?=URL;?>/return-city', function(data){
        var arr = []; 

        // Armazena no array
        $(data).each(function(key, value) {             
            arr.push(value.nome); //Guardo apenas o nome, 
           //porém preciso passar o id para posterior resgate
        });
        console.log(arr);

        $('#location').autocomplete({ source: arr, minLength: 3,
        select: function(event, ui) {
        var retorno = ui.item.value;
        console.log(retorno); 
        },

        });
    });

This is the return of my Json

[Object { nome="Acrelandia",  uf="AC",  id="0001"}, Object { nome="Assis Brasil",  uf="AC",  id="0002"}

In event select I need to know how to manipulate any value in the array be the name or id.

    
asked by anonymous 14.04.2016 / 07:29

1 answer

1

There is the possibility of passing the information in JSON into the array. In your case you should change from:

arr.push(value.nome);


To

 arr.push({label:value.nome, value:value.id});

So when you are writing, the name will appear, but when you select the id. Example in jsfiddle without ajax: link

    
14.04.2016 / 18:22