Created
August 6, 2016 02:38
-
-
Save joshuacerbito/ba147b3f777a498790a8aa46efe14acc to your computer and use it in GitHub Desktop.
Limit text input to numeric values
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
textInput.addEventListener('keydown', function (e) { | |
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 || | |
(e.keyCode == 65 && e.ctrlKey === true) || // Allow: Ctrl+A | |
(e.keyCode == 67 && e.ctrlKey === true) || // Allow: Ctrl+C | |
(e.keyCode == 88 && e.ctrlKey === true) || // Allow: Ctrl+X | |
(e.keyCode >= 35 && e.keyCode <= 39)) // Allow: home, end, left, right | |
{ return; } | |
// Ensure that it is a number and stop the keypress | |
if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) { | |
e.preventDefault(); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment