Getting multiple values ​​from json data using typeahead.js

I am having trouble accessing remote json data in typeahead.js . I tried to use an example of prefetching notes and searching using typeahead.js but was able to only get simple json notes with only values.

The json data file I used is data / notes_simple.json .

["Atomic Energy", "Introduction to Biology", ...]

      

The search result looks like this: (Shows only names)

Electromagnetism
Introduction to Biology

      

I want to use data / notes.json which contains keys and values .

[{
    "name": "Electromagnetism",
    "subject": "Physics",
    "form": "4"
}, {
    "name": "Introduction to Biology",
    "subject": "Biology",
    "form": "1"
...

      

The search result I want to display looks like this: (Shows name, subject and form / class)

Electromagnetism
Physics - Form 4

Introduction to Biology
Biology - Form 1

      

How can I get something like the above?

My js / prefetch.js looks like this:

$(function() {
    var notes = new Bloodhound({
        datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
        queryTokenizer: Bloodhound.tokenizers.whitespace,
        limit: 10,
        prefetch: {
            url: 'data/notes_simple.json',
            filter: function(list) {
                return $.map(list, function(country) {
                    return {
                        name: country
                    };
                });
            }
        }
    });

    notes.initialize();

    $('#prefetch .typeahead').typeahead(null, {
        name: 'notes',
        displayKey: 'name',
        source: notes.ttAdapter()
    });

});

      

You can find my hosted project here: http://goo.gl/7kPVk2

Any help is appreciated.

+3


source to share


1 answer


An example of how you can do something like this can be seen here:

http://jsfiddle.net/Fresh/u4fq85bj/

You will need to change the remote call to your notes.json and change the filter accordingly, eg.



remote: {
    url: '/notes.json',
    filter: function (notes) {
        return $.map(notes, function (note) {
            return {
                name: note.name,
                subject: note.subject,
                form: note.form
            };
        });
    }
}

      

To display the results in the format you want, you can use the Handlebars caption templating engine like this:

templates: {
 suggestion: 
  Handlebars.compile("<p>{{name}}</p><p>{{subject}} - Form {{form}}</i></p>")
    }

      

+1


source







All Articles