Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 462
Brian Powell Avatar asked Jun 06 '26 01:06

Brian Powell


1 Answers

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

like image 155
Kyle Avatar answered Jun 07 '26 16:06

Kyle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!