0

I have the following code and am trying to allow only 3 digits 0-9 in the input, but still allow the user to use the arrow keys, backspace, and delete keys.

It works in other browsers, but in firefox the output to the console shows the arrow keys and the delete key registering as key code 0. What gives?

Code:

$input.
    keypress(function(e) {
        var currentLength = $input.val().length;
        var c = e.which;
        console.log("key", c);
        //0=48, 9=57, 37-40 = arrow keys 8= backspace,  46=delete
        if (c === 8 || c === 46 || (c >= 37 && c <=40)) {
            //delete, backspace, and arrow keys are allowed
        } else if (c < 48 || c > 57 || currentLength >= 3) {
            e.preventDefault();
        }
    }).on("paste", function(e) {
        e.preventDefault();
    });

Fiddle: http://jsfiddle.net/2cjpdfcy/

thatidiotguy
  • 8,701
  • 13
  • 60
  • 105
  • On a minor note, event 'input' will only fire for keys that change the input value, so you wouldn't have to care about the arrow keys. – Taplar Nov 09 '15 at 18:01
  • @Taplar That is a great suggestion but unfortunately I have to still support IE 8 :( Thanks though! – thatidiotguy Nov 09 '15 at 18:03

2 Answers2

1

To get all the keycodes use keyup instead of keypress:

$input.keyup(function(e) {
    // your logic...
});

Updated fiddle

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • So that definitely works, but would you mind explaining WHY this is the case? What is different about the keyup event? Also do you have any comment on Sergio's solution which also works? – thatidiotguy Nov 09 '15 at 18:01
1

Replace this:

var c = e.which;

with :

var c = e.keyCode || e.which;

And all will work.

http://jsfiddle.net/2cjpdfcy/2/

Sergio Ivanuzzo
  • 1,820
  • 4
  • 29
  • 59