4

Below is my textbox:

<input type="number" id="payement-textbox'+index+'" name="payment-textbox" min="0" max="100000" step="any" maxlength="9" class="payment" placeholder="--" value=""/>;

There are two validation on my number type textbox. First is user cannot enter value bigger than 99999.99 which I applied successfully. The other one is that user cannot enter more than two digits after decimal which is not working.

Here is my jQuery code:

$('input.payment').on("change paste keyup", function(event) {
          var max = parseFloat($(this).attr('max'));
          var num = parseFloat($(this).val());
          if ( num >= max)
          {
              $(this).val("99999.99");
          }  
          if( ($(this).val().indexOf('.') != -1) && ($(this).val().substring($(this).val().indexOf('.')).length > 2))
          {
          event.preventDefault();
          }

        }); 

Could you please tell me where I am going wrong?

Shubhangi Garg
  • 109
  • 5
  • 17
  • Refer this link, hope so this will help you http://stackoverflow.com/questions/21796827/jquery-allow-only-two-numbers-after-decimal-point – Siddharth vyas Jul 11 '16 at 10:09
  • http://jsfiddle.net/S9G8C/203/ – rejo Jul 11 '16 at 10:09
  • Because it's being triggered **after** the input was already entered, you will want to use `keydown`. Just note you need a way for the user to delete the 2nd decimal (*ex: check for the 3rd decimal and remove the last digit*). – Spencer Wieczorek Jul 11 '16 at 10:09
  • 1) Why are you doing validation in jQuery if it's already set in the HTML? 2) Have you tried changing the `step` attribute? – gcampbell Jul 11 '16 at 10:10

2 Answers2

2

Try:

$("#yourinput").keyup(function(){
  var num = parseFloat($(this).val());
  if ( num >= 99999.99)
  {
    $(this).val("99999.99");
  }  
  
   var number = ($(this).val().split('.'));
   if (number[1] && number[1].length > 2)
   {
    var salary = parseFloat($("#yourinput").val());
    $("#yourinput").val( salary.toFixed(2));
   }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<input id="yourinput" pattern="\d+">
<span id=bad style="display:none;color:red">BAD</span>
Dhara Parmar
  • 8,021
  • 1
  • 16
  • 27
0

You need to use the keypress event so it will trigger before the input is entered.

This will work:

$('input.payment').on("keypress paste keyup", function(event){
    //Your code
})
Madalinul
  • 95
  • 1
  • 9