views:

38

answers:

2

I'm using this function to only allow numbers in a text input.

$('input').bind('keydown', function(e) {

    var key = e.charCode || e.keyCode || 0;

    return (
         key == 8 ||
         key == 9 ||
         key == 46 ||
         (key >= 37 && key <= 40) ||
         (key >= 48 && key <= 57) ||
         (key >= 96 && key <= 105));
});

How would I also allow copy and paste? I've tried adding keycode 17 for control but it still doesn't work.

Is there something special you have to do for key combinations?

Thanks

A: 

Keep a record of the last keycode pressed. Since you're using onkeydown, a cmd-v would show up as an event with keycode 224 (cmd) and then an event with keycode 86 (v). If the previous key matches cmd and the latter v, allow it through.

(you would probably check for ctrl for Windows/Linux pasters as well)

Nick
There are more ways than that to paste: from the context and edit menus, for example. There's also dragging.
Tim Down
+1  A: 

You better off with something like:

$('input').bind('keyup', function(e) {
  this.value = this.value.replace(/[^0-9]/g,'');
});

Or you can also use the change event. In this case no matter how the data gets into the field it will be validated (and non numeric input removed). ​

galambalazs
+1 for the simplicity and foolproofness of using the `change` event.
Tim Down