jQuery autocomplete: taking JSON input and setting multiple fields from single field

Posted by Sly on Stack Overflow See other posts from Stack Overflow or by Sly
Published on 2010-04-01T03:46:59Z Indexed on 2010/04/01 3:53 UTC
Read the original article Hit count: 539

Filed under:
|
|
|

I am trying to get the jQuery autocomplete plugin to take a local JSON variable as input. Once the user has selected one option from the autocomplete list, I want the adjacent address fields to be autopopulated.

Here's the JSON variable that declared as a global variable in the of the HTML file:

var JSON_address={"1":{"origin":{"nametag":"Home","street":"Easy St","city":"Emerald City","state":"CA","zip":"9xxxx"},"destination":{"nametag":"Work","street":"Factory St","city":"San Francisco","state":"CA","zip":"94104"}},"2":{"origin":{"nametag":"Work","street":"Umpa Loompa St","city":"San Francisco","state":"CA","zip":"94104"},"destination":{"nametag":"Home","street":"Easy St","city":"Emerald City ","state":"CA","zip":"9xxxx"}}}</script>

I want the first field to display a list of "origin" nametags: "Home", "Work". Then when "Home" is selected, adjacent fields are automatically populated with Street: Easy St, City: Emerald City, etc.

Here's the code I have for the autocomplete:

$(document).ready(function(){

$("#origin_nametag_id").autocomplete(JSON_address, {
    autoFill:true, 
    minChars:0, 
    dataType: 'json', 
    parse: function(data) {
        var rows = new Array();
        for (var i=0; i<=data.length; i++) {
            rows[rows.length] = { data:data[i], value:data[i].origin.nametag, result:data[i].origin.nametag };
        }   
        return rows;
    }
}).change(function(){
    $("#street_address_id").autocomplete({
      dataType: 'json',
      parse: function(data) {
        var rows = new Array();
        for (var i=0; i<=data.length; i++) {
            rows[rows.length] = { data:data[i], value:data[i].origin.street, result:data[i].origin.street };
        }   
        return rows;
      }  
    });
}); 

});

So this question really has two subparts: 1) How do you get autocomplete to process the multi-dimensional JSON object? (When the field is clicked and text entered, nothing happens - no list) 2) How do you get the other fields (street, city, etc) to populate based upon the origin nametag sub-array?

Thanks in advance!

© Stack Overflow or respective owner

Related posts about jQuery

Related posts about autocomplete