What am I missing in order to translate my jQuery onClick events into keypress events where a user can use a keypad?
The specific example is for a calculator. Using jQuery and the on click/touch events work perfect. However, when I try to introduce keyCodes I am not getting the results I think I should.
Here is my example code;
$(document).keypress(function(event){
var display = "0";
var keycode = (event.keyCode ? event.keyCode : event.which);
if(keycode === 13){
alert(keycode + " = ENTER");
calcDisplay(total(), true);
}
});
Most of this I picked up from other successful solutions to similar issues. So the way I understand it is; if someone presses "enter" on the keyboard, I'd get my alert and then process my answer.
The jQuery version of this that works for me looks like this;
$(".button").on("click touch", function(){
var button = $(this).data("value");
if(button === "="){
calcDisplay(total(), true);
}
superNewb to JS here so much love ahead of time if this is something super foolish on my end.
keypress
is meant to be used when characters are being inserted as input. keydown
is meant to be used to detect any key.
quirksmode has a nice little write-up about the differences.
Instead of $(document).keypress
use $(document).keydown
.
Additionally, jQuery normalizes event.which
, so instead of:
var keycode = (event.keyCode ? event.keyCode : event.which);
you can use
var key = e.which;