Skip to content

Instantly share code, notes, and snippets.

@samatsav
Created September 20, 2013 13:51
Show Gist options
  • Save samatsav/6637884 to your computer and use it in GitHub Desktop.
Save samatsav/6637884 to your computer and use it in GitHub Desktop.
Allow only numeric input inside text field
document.getElementsByTagName('input')[0].onkeypress = function(e) {
e = e || event
var chr = getChar(e)
if (!isNumeric(chr) && chr !== null) {
return false
}
}
// helper functions
function isNumeric(val) {
return val !== "NaN" && (+val)+'' === val + ''
}
function getChar(event) {
if (event.which == null) {
return String.fromCharCode(event.keyCode) // IE
} else if (event.which!=0 && event.charCode!=0) {
return String.fromCharCode(event.which) // the rest
} else {
return null // special key
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment