kurenai Kunai kurenai Kunai - 11 days ago 6
HTML Question

Text box to allow only decimal numbers, delete and backspace

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)">




Answer

I found the solution. Adding the code here for anyone who would be having the same requirements as I had.

/*
 *  Function to allow decimal numbers to be entered in the text box
 *   - allows integers, backspace and delete
 *   - does not allow alphabets
 *   - allows only one decimal point
 *   - allows only two digits after decimal point
 */
function isNumberKey(evt, element) {
  var charCode = (evt.which) ? evt.which : window.event.keyCode;
  if (charCode > 31 && (charCode < 48 || charCode > 57) && !(charCode == 46 || charCode == 8))
    return false;
  else {
    var len = $(element).val().length;
    var index = $(element).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)">

Thanks.