Skip to content

Instantly share code, notes, and snippets.

@joshuacerbito
Created August 6, 2016 02:38
Show Gist options
  • Save joshuacerbito/ba147b3f777a498790a8aa46efe14acc to your computer and use it in GitHub Desktop.
Save joshuacerbito/ba147b3f777a498790a8aa46efe14acc to your computer and use it in GitHub Desktop.
Limit text input to numeric values
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