1

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.

3
  • Your code should work. Here's a plunker with it working plnkr.co/edit/mvDnrOEiUPgmUKWBj5OD?p=preview . What does console.log(keycode); give you right before if(keycode === 13) Commented Apr 17, 2016 at 0:58
  • If you log keycode, what the value logged? Commented Apr 17, 2016 at 0:58
  • listen to keydown instead of keypress. Commented Apr 17, 2016 at 1:05

1 Answer 1

1

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;
Sign up to request clarification or add additional context in comments.

1 Comment

Magical! All of the operators are working as needed. Also, it appears that I was trying to execute this separately looking for the calcDisplay() function before it was defined. Haven't yet solved the numeric keycodes just yet but we're on the right path. Thank you all for the help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.