Reputation: 9386
I have something like this:
$('#find').click(function() {...
I need to also add to that event that if they press the enter key it will also execute.
I was thinking something along the lines of:
var code = (e.keyCode ? e.keyCode : e.which);
if ( ($('#find').click()) || (code == 13)) {
But obviously it does not work. How can I merge both ways into one. Pressing enter should work only when done in the input with id="code". The click event is for another input type button with id="find". I want to merge both that, if the user presses enter while typing the code or clicking the button to send the code, both ways work the same way.
Upvotes: 1
Views: 63
Reputation: 253308
Use on()
:
$('#find').on('click keypress', function(e){
if (e.type == 'click' || e.which == '13') {
// do stuff
}
});
References:
on()
.Upvotes: 1
Reputation: 2543
An extension on this is:
$('#find').on('click',function(event,params) {
// your click code here
}).on('keypress'),function(event) {
// if you have 13, then send the click evnet
// this way lets you do other things by passing the params
// object, if you wish
var code = (e.keyCode ? e.keyCode : e.which);
if(13 == code) {
$(this).trigger('click');
return false;
}
// other code that executes if code != 13
});
Upvotes: 0
Reputation: 6825
you can do it like this:
function myHandler(){
$(this).css('background-color', 'green'); //whatever you need to do here
}
$('#find').click(myHandler);
$('#find').keypress(function(){
var code = (e.keyCode ? e.keyCode : e.which);
if(code == 13) myHandler();
);
or maybe use keyup, you should read the docs on that: http://api.jquery.com/keyup/
Upvotes: 4