Skip to content

Instantly share code, notes, and snippets.

@tcurvelo
Last active July 21, 2016 13:30
Show Gist options
  • Save tcurvelo/33217dfd6c5488255c785db7def33712 to your computer and use it in GitHub Desktop.
Save tcurvelo/33217dfd6c5488255c785db7def33712 to your computer and use it in GitHub Desktop.
Restricting keys allowed to an input
document.getElementById('numbersonly').addEventListener(
'keypress',
function() {
var allowed_keys = {
48: true, // 0
49: true, // 1
50: true, // 2
51: true, // 3
52: true, // 4
53: true, // 5
54: true, // 6
55: true, // 7
56: true, // 8
57: true, // 9
8: true, // backspace
9: true, // tab
13: true, // enter
127: true, // delete
32: false // space
};
return function(event) {
var key = document.all ? event.keyCode : event.which;
if (!allowed_keys[key]) {
event.preventDefault();
}
};
}(),
false
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment