Skip to content

Instantly share code, notes, and snippets.

@Klerith
Last active May 14, 2022 22:54
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Klerith/45bafbc3278030477799 to your computer and use it in GitHub Desktop.
Save Klerith/45bafbc3278030477799 to your computer and use it in GitHub Desktop.
JavaScript: Only Numbers Class
/**
* Allow only numbers, backspace, delete, tab, escape, enter and dots.
* for HTML input box
*/
$(document).ready(function() {
$(".numberOnly").keydown(function (e) {
// Allow: backspace, delete, tab, escape, enter and .
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 190]) !== -1 ||
// Allow: Ctrl+A
(e.keyCode == 65 && e.ctrlKey === true) ||
// Allow: home, end, left, right
(e.keyCode >= 35 && e.keyCode <= 39)) {
// let it happen, don't do anything
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();
}
});
});
@Klerith
Copy link
Author

Klerith commented Oct 8, 2014

When you set an input with this particular class, it will only accept numbers and dots

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment