Search code examples
jquery-ui-autocomplete

How to convert JSON multidimentional array to javascript function for autocomplete list and how to assign selected list array values to input type


I get autocomplete list using the following code. But I want to assign other array values of selected list to input type.

$(document).ready(function()
{
    $(function () {
        var getData = function(request, response) {
        $.get(
            "autocomplete_locality1.php?callback=?&term=" + request.term,
            function(data) {
        data1 = jQuery.parseJSON(data);
        var res=[];
        for(var i in data1){
          if(data1.hasOwnProperty(i)){
            res.push(data1[i]['value']);
          }
        }
        response(res);
            });
    };
 
    $("#locality").autocomplete({
    minLength: 1,
    source: getData,
    focus: function(event, ui) {
        $("#locality").val(ui.item.label);
        return false;
    },
    select: function(event, ui) {
        $( "#locality" ).val(ui.item.label);
        $("#city").val(ui.item.city);
        $( "#ptype").val(ui.item.ptype);
        $( "#rcl").val(ui.item.rcl);
        return false;
    }
})
.data("autocomplete")._renderItem = function(ul, item) {
    return $("<li></li>")
        .data("item.autocomplete", item )
        .append("<table><tr><td>" + item.label + "</td></tr></table>")
        .appendTo(ul);
};
    
});
    
});

I got the following output from "autocomplete_locality1.php" [{"value":"Aher","label":"Aher","city":"Pune","rcl":"R","ptype":"Residential"},{"value":"Akruti,","label":"Akruti","city":"Pune","rcl":"L","ptype":"Land"}]


Solution

  • $(document).ready(function()
    {
        $(function () {
        var getData = function(request, response) {
            $.get(
                "autocomplete_locality1.php?callback=?&term=" + request.term,
                function(data) {
            data1 = jQuery.parseJSON(data);
            var res=[];
            for(var i in data1){
              if(data1.hasOwnProperty(i)){
                res.push({rcl:data1[i]['rcl'], value:data1[i]['value'], label:data1[i]['label'], ptype:data1[i]['ptype'], city:data1[i]['city']});
              }
            }
                    
            response(res);
                });
        };
     
        $("#locality").autocomplete({
        minLength: 1,
        source: getData,
        select: function(event, ui) {
            $("#locality").val(ui.item.value);
            $("#rcl").val(ui.item.rcl);
            $("#city").val(ui.item.city);
            $("#ptype").val(ui.item.ptype);
            return false;
        }
    })
    .data("ui-autocomplete")._renderItem = function(ul, item) {
            return $('<li title = "' + item.value + '">' + item.value + '</li>').appendTo(ul); 
    };
        
    });
        
    });