Allow only numeric input in textbox using jQuery
Allow only numeric input in textbox using jQuery
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("paste",function (event) {
var val = event.originalEvent.clipboardData.getData('Text'),
regex = /\d{0,4}([\.|\,]\d{0,2})?/;
x = regex.test(val);
console.log(val + ", " + x);
if(!x){
event.preventDefault();
}
});
$(".allownumericwithdecimal").on("keypress keyup",function (event) {
var val = $(this).val();
$(this).val(val.replace(/[^0-9\.\,]/g, ''));
if ((event.which == 46 || event.which == 190) && ($(this).val().indexOf('.') != -1 || $(this).val().indexOf(',') != -1) && (event.which < 48 || event.which > 57)) {
event.preventDefault();
}
else if ((event.which == 44 || event.which == 188) && ($(this).val().indexOf('.') != -1 || $(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();
}
});