Skip to content

Instantly share code, notes, and snippets.

@leomuniz
Last active March 30, 2024 00:53
Show Gist options
  • Select an option

  • Save leomuniz/0b0b00d8f3c73be92b0718513e371834 to your computer and use it in GitHub Desktop.

Select an option

Save leomuniz/0b0b00d8f3c73be92b0718513e371834 to your computer and use it in GitHub Desktop.
JavaScript snippet to allow only numbers when typing in an input field
jQuery.fn.onlyNumbers = function() {
return this.each(function() {
jQuery(this).keydown(function(e) {
var key = e.charCode || e.keyCode || 0;
return (
key == 13 || // Enter
key == 189 || // Minus symbol (-)
key == 8 || // Backspace
key == 9 || // Tab
key == 46 || // Delete
key == 186 || // Colon (:)
(key >= 37 && key <= 40) || // Arrows
(key >= 48 && key <= 57) || // Numbers
(key >= 96 && key <= 105) // Numbers (Num Lock)
);
});
});
};
// Usage
// jQuery( el ).onlyNumbers();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment