Skip to content

Instantly share code, notes, and snippets.

@jwaltonmedia
Created August 20, 2013 18:51
Show Gist options
  • Save jwaltonmedia/6285601 to your computer and use it in GitHub Desktop.
Save jwaltonmedia/6285601 to your computer and use it in GitHub Desktop.
This is a little plugin I wrote to ensure form fields only accept numbers as input
$.fn.numbersOnlyField = function() {
var element = this,
validKeys = [48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 8, 9],
currentValue;
function onkeydown_field(e) {
currentValue = element.val();
}
function onkeyup_field(e) {
var value = element.val();
if (/[\d]+$/g.test(value)) {
if (validKeys.indexOf(e.keyCode) < 0) {
element.val(currentValue);
}
} else {
element.val('');
}
}
element.on('keyup', onkeyup_field);
element.on('keydown', onkeydown_field);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment