How to prevent keypress two digits after a decimal number?

后端 未结 5 1999
花落未央
花落未央 2020-12-31 10:06

I have got a task to prevent keypress two digits after a decimal number. My jquery file is

$(function(){ 
    $(\'#name\').bind(\'paste\', function(){
             


        
5条回答
  •  感情败类
    2020-12-31 10:38

    You can handle the key event before keyup on keypress, if the input is not to our liking we can disable the event from occurring. Something like this:

    Update

    Unfortunately my original answer below fails on certain numbers that can't be represented accurately as a float. Here is another solution that checks the position of the '.' character against the length of the string with a handy helper function.

    jsFiddle

    $('.decimal').keypress(function (e) {
        var character = String.fromCharCode(e.keyCode)
        var newValue = this.value + character;
        if (isNaN(newValue) || hasDecimalPlace(newValue, 3)) {
            e.preventDefault();
            return false;
        }
    });
    
    function hasDecimalPlace(value, x) {
        var pointIndex = value.indexOf('.');
        return  pointIndex >= 0 && pointIndex < value.length - x;
    }
    

    Original answer

    jsFiddle

    $('.decimal').keypress(function (e) {
        var character = String.fromCharCode(e.keyCode)
        var newValue = this.value + character;
        if (isNaN(newValue) || parseFloat(newValue) * 100 % 1 > 0) {
            e.preventDefault();
            return false;
        }
    });
    

    Note that parseFloat(newValue) * 100 % 1 > 0 evaluates to true if newValue contains a number that has more than 2 decimal places.

提交回复
热议问题