Manipulate Jquery autocomplete ui

Asked

Viewed 474 times

1

I am implementing in a system the query through an input using the Jquery UI Autocomplete. In practice when consulting a value by field name(Ex: São) my input will display a list of 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 for user view/selection.

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

Already in my Jquery script I have a variable of type array in which I store the query data. I believe my problem is here, because I am not able to store it in a way that I can catch the 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"}

At the event select i need to know how to handle any array value be the name or id.

  • Hello, for what I understood with the name is everything going well. Now intends to have possibility to manipulate the ids?

  • Yes, I can manipulate the nome at the event SELECT as the one I select from the list. However the name only serves for the user to select the city. In the background when selecting a city by the field nome I need to manipulate the id of the same to insert in a database.

1 answer

1


There is the possibility to pass the JSON information inside the array.

In your case you should change from.:

arr.push(value.nome);


To

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

So when they are writing the name will appear but when selecting the id.
Example in jsfiddle without ajax.: http://jsfiddle.net/q6jGr/193/

  • Your response was important to my understanding of the handling of JSON in Autocomplete. In my case I needed the input to display the name, but the event select should hear the id. So I implemented arr.push({label:value.nome, id:value.id}) and in the parameter captured the id defining: ui.item.id;

Browser other questions tagged

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