Skip to content

Instantly share code, notes, and snippets.

@sampathsl sampathsl/numeric-input.js
Last active Oct 21, 2016

Embed
What would you like to do?
How to restrict an input field to a numeric input field using JavaScript
/*
* Avoid the A-Z a-z and special characters in text boxes
*/
jQuery(document).on('keypress', 'input.numeric', function(e) {
/* avoid entering multiple '.' */
if (e.currentTarget.value)
{
var keyCode = e.which ? e.which : e.keyCode;
var c = String.fromCharCode(keyCode);
/* fix DEL key for FF */
if (e.which == '0')
{
return true;
}
/* for avoid multiple '.' */
else if (c === '.' && e.currentTarget.value.indexOf('.') > -1)
{
return false;
}
/* disable space bar */
else if (keyCode === 32){
return false;
}
}
if (navigator.appName == "Opera")
{
var c = String.fromCharCode(e.keyCode);
if (/[\%\_']/.test(c))return false;
else if ((e.keyCode == 37)// left
|| (e.keyCode == 8)// backspace
|| (e.keyCode == 9)// tab
|| (e.keyCode == 39)// right
)return true;
else if (/[ \d\.]/.test(c))return true;
else return false;
}
else if (navigator.appName == "Netscape")
{
var c = String.fromCharCode(e.charCode);
if (/[\%\_']/.test(c))return false;
else if ((e.keyCode == 37)// left
|| (e.keyCode == 8)// backspace
|| (e.keyCode == 9)// tab
|| (e.keyCode == 39)// right
|| (e.keyCode == 46)// DEL
)return true;
else if (/[ \d\.]{1,}$/.test(c))return true;
else return false;
}
else if (/Microsoft/.test(navigator.appName))
{
var c = String.fromCharCode(e.keyCode);
if (/[\%\_']/.test(c))return false;
else if ((e.keyCode == 37)// left
|| (e.keyCode == 8)// backspace
|| (e.keyCode == 9)// tab
|| (e.keyCode == 39)// right
)return true;
else if (/[ \d\.]/.test(c))return true;
else return false;
}
else
{
var CharKey = (e.keyCode) ? e.keyCode : e.charCode;
var c = String.fromCharCode(CharKey);
if (/[\%\_']/.test(c))return false;
else if ((e.keyCode == 37)// left
|| (e.keyCode == 8)// backspace
|| (e.keyCode == 9)// tab
|| (e.keyCode == 39)// right
)return true;
else if (/[ \d\.]/.test(c))return true;
else return false;
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.