Skip to content

Instantly share code, notes, and snippets.

@jayde
Created July 4, 2013 16:34
Show Gist options
  • Save jayde/5928986 to your computer and use it in GitHub Desktop.
Save jayde/5928986 to your computer and use it in GitHub Desktop.
Makes sure that <input type="number"> only accepts numbers and not letters.
// make sure that input type="number" only accepts numbers
$.fn.allowNumbersOnly = function() {
$(this).keydown(function (event) {
var num = event.keyCode;
if ((num > 95 && num < 106) || (num > 36 && num < 41) || num == 9) {
return;
}
if (event.shiftKey || event.ctrlKey || event.altKey) {
event.preventDefault();
} else if (num != 8 && num != 46 && num != 109 && num != 110 && num != 188 && num != 189 && num != 190) {
// 8 backspace, 46 delete, 109 subtract, 110 decimal, 188 comma, 189 dash, 190 period
// reference: http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes
if (isNaN(parseInt(String.fromCharCode(event.which)))) {
event.preventDefault();
}
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment