Last active
March 30, 2024 00:53
-
-
Save leomuniz/0b0b00d8f3c73be92b0718513e371834 to your computer and use it in GitHub Desktop.
JavaScript snippet to allow only numbers when typing in an input field
This file contains hidden or 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
| 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