0

Allow only numeric input in textbox using jQuery

Today i am going to share how you validate a textbox only for numeric input
HTML Code

[code language=”html”]
<span>Float</span>
<input type="text" name="numeric" class=’allownumericwithdecimal’>
<div>Numeric values only allowed (With Decimal Point) </div>
<br/> <br/> <br/>

<span>Int</span>
<input type="text" name="numeric" class=’allownumericwithoutdecimal’>
<div>Numeric values only allowed (Without Decimal Point) </div>
[/code]

JQuery Code

[code language=”js”]
$(".allownumericwithdecimal").on("keypress keyup blur",function (event) {
//this.value = this.value.replace(/[^0-9.]/g,”);
$(this).val($(this).val().replace(/[^0-9.]/g,”));
if ((event.which != 46 || $(this).val().indexOf(‘.’) != -1) && (event.which < 48 || event.which > 57)) {
event.preventDefault();
}
});

$(".allownumericwithoutdecimal").on("keypress keyup blur",function (event) {
$(this).val($(this).val().replace(/[^d].+/, ""));
if ((event.which < 48 || event.which > 57)) {
event.preventDefault();
}
});
[/code]

Click Here for Demo

Sandeep Kumar

Sandeep kumar is a web developer and a professinal blogger. He works for latest technologies and write articles what he learn. In ICodeHub he share web languages tutorials and other programming tips and tricks. if you need some help or have some suggestion then mail him at sandeep92pal@gmail.com without any hesitation. He believes in learning and sharing.