h4kl0rd
h4kl0rd

Reputation: 625

Retrieving multiple values from json data using typeahead.js

I'm having trouble accessing remote json data into typeahead.js. I tried using prefetch example to retrieve notes and be able to search using typeahead.js, but was able to fetch only simple json notes with only values.

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

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

The search result appears as follows: (Shows only names)

Electromagnetism
Introduction to Biology

I want to be able 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 appear is as follows: (Shows name, subject and form/class)

Electromagnetism
Physics - Form 4

Introduction to Biology
Biology - Form 1

How can I get something like above?

My js/prefetch.js looks as below:

$(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.

Upvotes: 3

Views: 2470

Answers (1)

Ben Smith
Ben Smith

Reputation: 20230

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

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

You would need to change the remote call to your notes.json, and modify the filter appropriately e.g.

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 your desired format you could use the Handlebars template engine with mark-up as follows:

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

Upvotes: 1

Related Questions