简体   繁体   中英

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM