Pages

Social Icons

Wednesday 23 November 2011

Allow only numeric character in JavaScript

Hi,


Here is the example code of Javascript which allows you to type only numeric value in a textbox.


Here is the features of this code :

  • It allows only numeric value with decimal point.
  • It allows only one decimal point in a textbox.
  • It allows only two character after decimal point.

$("#txtExample").keydown(function (event) {
var a = $("#txtWeightChangePercent").val();
var len = '';
if ((a.indexOf('.') - 1) == 0)
len = a.length - a.indexOf('.') - 1;
else
len = a.length + (a.indexOf('.') - 1);

if (len > 1 && event.keyCode != 8) {
event.preventDefault();
}

if (event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 190 || event.keyCode == 110) {
if ((a.split(".").length - 1) > 0 && event.keyCode != 8) {
event.preventDefault();
}
// Some thing goes here
}
else {
// Ensure that it is a number and stop the keypress
if ((event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105) && (event.keyCode <= 42 || event.keyCode >= 40) && (event.keyCode <= 33 || event.keyCode >= 45)) {
event.preventDefault();
}
}
});


If you don't want to allow decimal also then remove this "|| event.keyCode == 190 || event.keyCode == 110" 
Thx,
RS

No comments:

Post a Comment