Skip to content

Instantly share code, notes, and snippets.

@lfalmeida
Last active August 29, 2015 14:23
Show Gist options
  • Save lfalmeida/147ce64d293d3059c291 to your computer and use it in GitHub Desktop.
Save lfalmeida/147ce64d293d3059c291 to your computer and use it in GitHub Desktop.
inputNumbers.js
(function ($) {
$.fn.onlyNumbers = function () {
return this.each(function () {
$(this).keydown(function (e) {
// backspace, delete, tab, escape, enter and .
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
// Ctrl+A, Command+A
(e.keyCode == 65 && (e.ctrlKey === true || e.metaKey === true)) ||
// home, end, left, right, down, up
(e.keyCode >= 35 && e.keyCode <= 40)) {
// 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();
}
});
});
};
}(jQuery));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment