Skip to content

Instantly share code, notes, and snippets.

@qwertypants
Created November 10, 2010 17:48
Show Gist options
  • Save qwertypants/671211 to your computer and use it in GitHub Desktop.
Save qwertypants/671211 to your computer and use it in GitHub Desktop.
Only allow numbers in an input field
$.fn.numOnly = function() {
return this.each( function() {
// backspace(8), dot(.), tab(0) 0-9
var c = [8, 0, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58];
if ($(this).attr('type') === 'text') {
$(this).keypress( function(e) {
if (c.indexOf(e.which, c) == -1) {
e.preventDefault();
}
});
}
});
};
@qwertypants
Copy link
Author

Whaddaya know, a ~4% speed increase! :P

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