Only Allow Numbers In An Input With Javascript And Allow Copy And Paste?
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
Solution 1:
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).
Solution 2:
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)
Post a Comment for "Only Allow Numbers In An Input With Javascript And Allow Copy And Paste?"