user2942566
user2942566

Reputation: 455

How to perform Autocomplete on json object

I have a json object as follows:

var subaccounts = [
{
    "name": "account 12200002 inc",
    "id": "3e55979f46304334b1de3b17fe0942d7",
    "billingContactInfo": {
      "country": "USA",
      "email": "[email protected]",
      "firstName": "poojas",
      "lastName": "wagh",
       "address1": "1234 asdf",
        "address2": "",
         "city": "mountain view",
         "phone": "",
         "postalCode": "95035",
         "stateOrProvince": "CA",
         "fax": ""
   }

} ]

For autocomplete i tried this:

selectedSubAccount = _.each(subaccounts, function(account) { 
                            return account.name
                        }); // to get the account name in the input field
$( "#autocomplete" ).autocomplete({
                        source: selectedSubAccount[0].name
                        
                        }); 

Below is the html:

<input id="autocomplete" placeholder = "search">

However when i type into the input field, it gives me this error:

GET http://home.stagingwpm.neustar.biz/account%2012200002%20inc?term=a 404 (Not Found) 

Im not sure if this is the correct way to do the autocomplete: Anyone for any ideas? Please and thanks!

EDIT:::::

My selectedSubAccount gives me the following o/p.

enter image description here

so my "name" and "id" fields are below the "billingContactInfo". how can i make it an array containing only names for me to usesource: selectedSubAccount: ?

Thanks

Upvotes: 1

Views: 194

Answers (1)

padarom
padarom

Reputation: 3648

According to the Autocomplete Widget API Documentation:

String: When a string is used, the Autocomplete plugin expects that string to point to a URL resource that will return JSON data. It can be on the same host or on a different one (must provide JSONP). The Autocomplete plugin does not filter the results, instead a query string is added with a term field, which the server-side script should use for filtering the results. For example, if the source option is set to "http://example.com" and the user types foo, a GET request would be made to http://example.com?term=foo. The data itself can be in the same format as the local data described above.

In your example the source is of the type string, and therefore it expects it to be a URL to return the JSON. Your variable selectedSubAccount should however be an array consisting only of the names (you assign it in your _.each-loop) and should therefore be a valid source. So try to use the following source instead:

source: selectedSubAccount

Upvotes: 1

Related Questions