views:

151

answers:

2

Hey everyone,

I'm trying to make an autocomplete form using jquery, but I've run into an issue. I'm trying to make it so that when a user starts typing in the name of a place that's in our database, it shows them the full name of the place in the autocomplete, but when they click on it, the textbox gets filled with the address of the place that can be located with google maps. What would be the best way to accomplish this?

A: 

Probably pass in the entire "Person" object into javascript using a JSON object. Then you can pick and choose where you want each piece of the object to go.

zodeus
+2  A: 

Here a very rough sketch of some code that will get you started. By no means is it complete, but it should give you a good jumping off point. Hope it helps

$("#mySearchBox").change(function(){
/*
 send a ajax request to receive a json object.
 We use the callback function to populate the 
 a div tag "autocomplete" with the names
*/
$.getJSON("http://myurl.com/myPage?search="+$(this).val()
  function(data){
    $.each(data.items, function(i,item){
   /*
    Assume item looks like this

    item = {[{"address": 100 Main st",
         "name": "Bob and Joe's Dinner"],
       ...
        }
   */    
    /* Populate autocomplete with new spans
       We use the text attribute to hold the address
       You may want to look in to jquery data() feature. 
    */
    $("#autoComplete").append('<span text="'+ item.address +
            '" class="searchResult">'+ item.name +'</span>');
    });
  });

});

$("#autoComplete .searchResults").click(function(){
    /* 
     Here we handle what the user clicks on.
     Pull out the address from the attr and 
     put that back in the mySearchBox
    */
    var address = $(this).attr("text");

    //Load the adress back int the textfield
    $("#mySearchBox").val = address;
});
Scott