Ad Code

jQuery Allow Numbers and Decimal only in Textbox [numeric]

# Download and import jQuery library.

//*
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js">
</script>
</head>
//*

 

HTML Markup: Adding two textbox for validation.

//*
<table>
  <tr>
 <td><strong>Int value:</strong></td>
 <td>
 <input type="text" name="numeric" class='allow_numeric'>
 <div>Allow only numeric values (without decimal) </div>
 </td>
  </tr>
  <tr>
 <td> <strong>Decimal :</strong></td>
 <td>
 <input type="text" name="numeric" class='allow_decimal'>
 <div>Allow numeric values with decimal</div>
 </td>
  </tr>
</table>
//*

 

Jquery: Code to allow only numeric values.

//*
$(".allow_numeric").on("input", function(evt) {
    var self = $(this);
    self.val(self.val().replace(/[^\d].+/, ""));
    if ((evt.which < 48 || evt.which > 57)) 
     {
    evt.preventDefault();
     }
 });
//*

 

Jquery: Code to allow numbers and decimal values in the textbox.

//*
$(".allow_decimal").on("input", function(evt) {
   var self = $(this);
   self.val(self.val().replace(/[^0-9\.]/g, ''));
   if ((evt.which != 46 || self.val().indexOf('.') != -1) && (evt.which < 48 || evt.which > 57)) 
   {
     evt.preventDefault();
   }
 });
//*

 

Post a Comment

0 Comments