Search code examples
javascriptjqueryajaxtwitter-bootstrapbootstrap-typeahead

Bootstrap-3-Typeahead getting right json key


I am useing this plugin for an ajax auto complete feature https://github.com/bassjobsen/Bootstrap-3-Typeahead the bootstrap-3 type. The code below is working but I do not know why it works. Specifically how the the process and response parameter work.

$(document).ready(function() {
    $('#typeahead-input').typeahead({
        autoSelect: true,
        minLength: 1,
        delay: 400,
        source: function (query, process) {
            $.ajax({
                url: '/api/location',
                data: {sstr: query},
                dataType: 'json'
            })
                .done(function(response) {

                    // console.log(response)
                    return process(response);
                });
        }
    });
});

my json looks like this

[
    {
        "id": "123", 
        "name": "Frederiksted", 
        "state": "VI", 
        "zip_code": "840"
    }
]

What if i wanted to autocomplete to populated based on on the zip_code field how would i do it? I have tried doing "response.zipcode" but it comes out as undefined


Solution

  • First, response.zipcode will be undefined because response is a Array not a Object. You access zipcode by response[0].zip_code ( And also note that your property name is not 'zipcode' it is 'zip_code' ).

    Second, documentation of the "source" property says: The data source to query against. May be an array of strings, an array of JSON object with a name property or a function.

    So, what you give to the "process" method most probably should be a array of strings or array of JSON objects where each JSON object has a "name" property. If your response is correct and returns an array of objects like you say, then it means your objects each have a 'name' property,so that property is displayed. If you want to display something else, you need to create a new String array from the response:

    So I would try this:

     .done(function(response) {
         // get the response and create a new array of Strings
         var names = $.map (response, function(item) {
              return item.name + '-' + item.zip_code;
         });
         // console.log(response)
         return process(names);
        });
    

    or another way:

    .done(function(response) {
     // get the response and change the 'name' of each object
     $.each (response, function() {
           this.name = this.name + '-' + this.zip_code;
     });
     // console.log(response)
     return process(response);
    });