I'm using Twitter Typeahead to generate suggestions. My Ajax request is returning a complex data type, which is displayed nicely in the suggestions section. When the user selects one suggestion, I'd like to save the item's ID to a hidden field, and the item's name + color to the input field. As I've read in the documentation, I'd have to override the display method in the Typeahead constructor (or whatever it's called in JS), something like this:
display: function(item) {
$("#idhiddenfield").val(item.id);
return item.name + " " + item.color;
}
There are two problems with this: first, it's fired when the suggestion appears, rather than selecting it (display seems strange to me, but the docs state it's the correct method, in my opinion it should be select or something), also, if I leave the field and click back on it, it fires the Ajax call, which shows "No results found" (because name + color combination is not queryable on the server side) which is certainly bad.
Can someone help me with these two issues?
I think you misinterpreted the docs here. The display function is to determine the String which is displayed in the suggestion.
You can react on a selection of a suggestion with the typeahead:select
- Event on the input
-Element. e.G.:
$("#typeAheadInput").on("typeahead:select", function(event){ //Your logic here});
I would suggest to move your logic to a named-function and not use an inline anonymous function for better readability.
$("#typeAheadInput").on("typeahead:select", yourNamedFunction);