I have a autocomplete search field (typeahead.js) and I have a behaviour triggered when clicking on a search suggestion ie on click
.
I would like the same behaviour triggered when arrowing down and pressing enter on a suggestion.
So I would like the behaviour to occur on click
or on pressing enter
.
In the example below, I use an input field rather than replicating the full typeahead.js search scenario.
The problem with the code below is that it is only triggered when pressing enter in the input field (because of the conditional attached to e
) and not on click
.
HTML
<input class="hello" value="hello">
jQuery
$(document).on("click keypress",".hello", function (e) {
if (e.which == 13) {
alert($(this).val());
}
});
jsFiddle
http://jsfiddle.net/rwone/9xhK3/
Edit:
Updated jsFiddle with typeahead code:
Solution
After seeing this post:
https://stackoverflow.com/a/18710896/1063287
this code:
http://codepen.io/Sinetheta/pen/eAwcl
and this resource:
https://github.com/twitter/typeahead.js/issues/300
function searchFunction() {
$('.my_class .typeahead').typeahead({
name: 'my_name',
valueKey: 'my_key',
prefetch: 'path/to/json.json',
template: [
'<p class="key1">[[key_1]]</p>',
'<p class="my_key">[[my_key]]</p>',
'<p class="key3">[[key_3]]</p>'
].join(''),
engine: Hogan
}).on('typeahead:selected', function(event, selection) {
var my_key = selection.my_key;
alert(my_key);
});
}