Allow only numeric input in textbox using jQuery

Allow only numeric input in textbox using jQuery

by Yamini Sontakke

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>

JavaScript

$(".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();
   }
 });