Created
November 10, 2010 17:48
-
-
Save qwertypants/671211 to your computer and use it in GitHub Desktop.
Only allow numbers 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
$.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(); | |
} | |
}); | |
} | |
}); | |
}; |
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!
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
Thanks! I updated it using a regular expression and it's a bit over 1% faster (fugit, why not!).