Typehhead bootstrap, trigger when an item is selected or focused on the menu and receives a value

With bootstrap typeahead, I would like to run when an item is selected or focused from the menu to set a specific value related to the selected value.

Please read the code comments to understand exactly what I mean.

element.typeahead({ minLength: 3, source: function () { // users is a Backbone.Collection users = _.map(users, function(user) { return user.get('first_name')+' '+user.get('last_name'); }); return users; } }).change(function (event) { // this function which is called when the user set a value // should be able to get the user.get('id') of the selected user // any idea how to make it? }); 
+4
source share
1 answer

This may be useful for you. I use the extension for Typeahead, which allows you to call remote data sources. It comes with the onselect() callback function, where you can do what you want.

typeahead gist extension

Here is a sample code:

  initialization: function() { this.user = new User(); // Or fetch the user so it has an id, etc. }, initTypeahead: function() { var self = this; var element = this.$('#input'); element.typeahead({ source: userCollection.toJSON(), property: 'name', onselect: function(userObj) { // This is the line to pay attention to var userModel = userCollection.get(userObj.id); // Do something with the userModel } }); } 

So basically in my code, when I query my DB, I return a JSON that sets the value of each selection for any data that I transferred from my ajax.

With onselect(obj) I pass obj to my callback, and I just attach it as data to the input element. But you can easily add your own code that uses the user data (user.id) that you already have, and do what you do, along with the value that you have chosen of your choice. The value of user.id should be available in your onselect() as long as it is in the right amount of things.

+4
source

All Articles