Brian Powell
Brian Powell

Reputation: 3411

typeahead method to return associated results

I'm not sure to properly title this, but what I need to do is rather simple in theory. I've used Twitter's typeahead.js in the past to lookup values out of a pre-defined list. However, now I need to return something other than what the user types in, based on what they type in.

I have a list of names and IDs - the user will know the name, but not the IDs. When they type in the name, the dropdown needs to drop down any ID associated with that name.

Will the typeahead.js framework work for this? If so, how do I do it? I can't find any documentation online (or else I don't know what to search for...)

My JSON will look like this:

    {
    "1": {
        "name": "John",
        "ID": "1234"
    },
   "2": {
        "name": "Bob",
        "ID": "2345"
    },
   "3": {
        "name": "Matt",
        "ID": "3456"
    },
   "4": {
        "name": "John",
        "ID": "9874"
    }
}

So If the user types in "John" I want the dropdown to return two values:

1234
9874

I am not opposed to using something other than typeahead.js if it doesn't have this functionality.

Upvotes: 3

Views: 190

Answers (1)

Kyle
Kyle

Reputation: 1503

typeahead.js is still a fine choice for what you're trying to accomplish.

here is a fiddle with a working example:

https://jsfiddle.net/5fspsx79/

var substringMatcher = function(strs) {
 return function findMatches(q, cb) {
   var matches, substringRegex;
   matches = [];
   substrRegex = new RegExp(q, 'i');
   $.each(strs, function(i, str) {
     if (substrRegex.test(str.name)) {
       matches.push(str);
     }
   });
   cb(matches);
 };
};

var people = [{
    "name": "John",
    "ID": "1234"
},{
    "name": "Bob",
    "ID": "2345"
},{
    "name": "Matt",
    "ID": "3456"
},{
    "name": "John",
    "ID": "9874"
}];

$('#custom-templates .typeahead').typeahead(null, {
  name: 'people',
  display: 'ID',
  source: substringMatcher(people),
  templates: {
    empty: [
      '<div class="empty-message">',
       'unable to find any results.',
       '</div>'
     ].join('\n'),
   suggestion: Handlebars.compile('<div>{{ID}}</div>')
  }
});

You just need to add custom template.

There is an example at: http://twitter.github.io/typeahead.js/examples/

specifically, look at Custom Templates

Upvotes: 2

Related Questions