1

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:

http://jsfiddle.net/rwone/9xhK3/10/

user1063287
  • 10,265
  • 25
  • 122
  • 218
  • possible duplicate of [Trigger an event on \`click\` and \`enter\`](http://stackoverflow.com/questions/9146651/trigger-an-event-on-click-and-enter) – Pbk1303 Dec 29 '13 at 10:39

2 Answers2

2

I guess you need to find the event type and just or it

$(document).on("click keypress",".hello", function (e) {
    if(e.which == 13 || e.type == "click") {
       alert($(this).val());
    }
});
niko
  • 9,285
  • 27
  • 84
  • 131
  • Unfortunately, this is not working with `typeahead.js`, see updated jsFiddle with included typeahead code: http://jsfiddle.net/rwone/9xhK3/10/ – user1063287 Dec 29 '13 at 12:47
  • This does not work unfortunately - goals are to 1) alert when clicking on suggestion 2) alert when, after entering some text, arrowing down and pressing enter on suggestion. – user1063287 Dec 30 '13 at 01:45
0

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);
});
}
Community
  • 1
  • 1
user1063287
  • 10,265
  • 25
  • 122
  • 218