Autocomplete with json data

2.7k views Asked by At

I have two problems with this code:

json example:

{"json_list": [{"label": "Porto Rico", "value": 33}, {"label": "Portugal", "value": 32}]}

$("#user_country_name").autocomplete({
    source : function(request, response) {
        $.getJSON("/users/autocomplete/" + request.term, function(data) {
            response(data.json_list);
        });
    },
});

First when I choose a country the selected value in the input box should be the label and not the value. Because the user should see the country and not the id.

Second, how can I populate the hidden field $("#user_country_id") for the id of the chosen country?

2

There are 2 answers

1
elzi On BEST ANSWER

Use the select method

select: function( event, ui ) {
  event.preventDefault();
  $("#user_country_name").val(ui.item.label);
}
0
ariel_556 On

What you need to do, is to parse the json response. if you have any problems to get access use console.log().

$( "#w-arrival-search" ).autocomplete({
        select: function (e, ui) {
            $("#w-arrival-search").val(ui.item.label);
            return false;
        },
        minLength: 3,
        source: function (request, response) {
            $.ajax({
                url: 'http://localhost:8080/mvn/autocomplete',
                data: request,
                success: function (data) {
                    var ParsedObject = $.parseJSON(data);
                    response($.map(ParsedObject, function (item) {
                        var results = item.iata_code + " - " + item.city_name;
                        return {
                            label: results
                        };

                    }));
                }
            });
        }
    });