Text box to allow only decimal numbers, delete and rewind

advertisements

I have a code that works fine for decimal numbers allowing only two digits after the decimal. My question is how to modify the code to :

  1. Allow backspace and delete And
  2. How to make the code dynamic so that it does not use the id attribute instead pass the element in the method on the html and accept and use that element in javascript/jquery.

Here is my code:

function isNumberKey(evt, element) {
  var charCode = (evt.which) ? evt.which : event.keyCode
  if (charCode > 31 && (charCode < 48 || charCode > 57))
    return false;
  else {
    var len = $('#rate').val().length;
    var index = $('#rate').val().indexOf('.');

    if (index > 0 && charCode == 46) {
      return false;
    }
    if (index > 0) {
      var CharAfterdot = (len + 1) - index;
      if (CharAfterdot > 3) {
        return false;
      }
    }

  }
  return true;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" class="form-control" id="rate" name="rate" placeholder="Billing Rate" required onkeypress="return isNumberKey(event,this)">

Add a class to your textbox, say number here and below code will do it for you:

DEMO

$('.number').on('keypress',function (event) {
    if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
        event.preventDefault();
    }
    var text = $(this).val();
    if ((text.indexOf('.') != -1) && (text.substring(text.indexOf('.')).length > 2)) {
        event.preventDefault();
    }
});

Note: Your code was not allowing to enter . in textbox