Last active
July 21, 2016 13:30
-
-
Save tcurvelo/33217dfd6c5488255c785db7def33712 to your computer and use it in GitHub Desktop.
Restricting keys allowed to an input
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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