JQuery allow only two numbers after decimal point

前端 未结 7 913
春和景丽
春和景丽 2020-12-02 10:31

I found the following JQuery function here which prevents a user from entering anything that\'s not a number or a single decimal. The function works well but I\'d like to i

相关标签:
7条回答
  • 2020-12-02 11:30

    Numeric values With Decimal Point up to 2 decimal point validation. Dependency jQuery.

    HTML -

    <span>Float</span>
    <input type="text" name="numeric" class='allownumericwithdecimal'>
    <div>Numeric values only allowed  (With Decimal Point) </div>
    

    JQuery Code -

    Method 1-

        $(".allownumericwithdecimal").on("keypress keyup blur", function (event) {
         var patt = new RegExp(/[0-9]*[.]{1}[0-9]{2}/i);
         var matchedString = $(this).val().match(patt);
         if (matchedString) {
             $(this).val(matchedString);
         }
         if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
             event.preventDefault();
         }
     });
    

    Method 2 -

     $(".allownumericwithdecimal").on("keypress keyup blur", function (event) {
         var patt = new RegExp(/(?<=\.\d\d).+/i);
         $(this).val($(this).val().replace(patt, ''));
    
         if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
             event.preventDefault();
         }
     });
    
    0 讨论(0)
提交回复
热议问题