Skip to content

Instantly share code, notes, and snippets.

@qwertypants
Created November 10, 2010 17:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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();
}
});
}
});
};
@roc
Copy link

roc commented Jun 10, 2011

Maybe you could do a mixture of key chars and a regexp? No idea which is more efficient (though would think regular expression route would probably be pretty quick), ( /^[0-9]+$/ || {keypresses} ) as your test?

@qwertypants
Copy link
Author

Thanks! I updated it using a regular expression and it's a bit over 1% faster (fugit, why not!).

@roc
Copy link

roc commented Jun 15, 2011

hahaha bloody hell! Well that's not quite the performance improvement I was expecting. Perhaps an indexOf will bump it a little more ala http://jsperf.com/exec-vs-match-vs-test-vs-search/5 but whatever, good rev!

@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