Sunday, January 19, 2014

Allow only decimal or integer numbers in a 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>

Below code will allow user to enter only decimal numbers:

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


Below code will allow user to enter only integer numbers:

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

No comments:
Write comments
Recommended Posts × +