How to prevent keypress two digits after a decimal number?

后端 未结 5 1978
花落未央
花落未央 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:21
    $("#salary").keyup(function(){
        var number = ($(this).val().split('.'));
        if (number[1].length > 2)
        {
            var salary = parseFloat($("#salary").val());
            $("#salary").val( salary.toFixed(2));
        }
      });
    

    http://jsfiddle.net/calder12/fSQpc/

    Stop letters from going in the box, you'll have to put the two together I haven't time.

        if (this.value.match(/[^0-9]./g)) {
          this.value = this.value.replace(/[^0-9]./g, '');
          return false;
        }
    
    0 讨论(0)
  • 2020-12-31 10:33

    I did it this way: Provided a class allow-only-numbers, for your input then:

      var numberOfDecimals = 2;
      $(document).on("input", ".allow-only-numbers", function () {
        var regExp = new RegExp('(\\.[\\d]{' + numberOfDecimals + '}).', 'g')    
        this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1').replace(regExp, '$1');
    });
    
    0 讨论(0)
  • 2020-12-31 10:35

    This might be helpful to some. I mixed the answers of this guy, @Tats_innit from https://stackoverflow.com/a/10514166/5382523 and @Rick Calder above.

    EDIT also from this guy, isJustMe from https://stackoverflow.com/a/17289322 for the parseFloat with "|| 0". Because if the input's field is null or zero "NaN" is shown and you can't delete it.

    HTML

    <input type="text" name="txt_prod_price" id="txt_prod_price" class="form-control price" maxlength="20" placeholder="">
    

    JAVASCRIPT (JQUERY)

    $('.price').keypress(function(event) {
    
              if(event.which < 46 || event.which > 59) {
                  event.preventDefault();
              } // prevent if not number/dot
    
              if(event.which == 46 && $(this).val().indexOf('.') != -1) {
                  event.preventDefault();
              } // prevent if already dot
    
              var number = ($(this).val().split('.'));
              if (number[1].length > 2)
              {
               var price = parseFloat($("#txt_prod_price").val()) || 0;
               $("#txt_prod_price").val(price.toFixed(2));  
              }
    
          });
    

    the "price" is pre-defined.

    Note: still have buggy inputs but still kickin'. (y)

    More info about toFixed - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-31 10:44

    Another Possible Solution(Demo):

    Number.prototype.toFixedDown = function(digits) {
      var n = this - Math.pow(10, -digits)/2;
      n += n / Math.pow(2, 53); // added 1360765523: 17.56.toFixedDown(2) === "17.56"
      return n.toFixed(digits);
    }
    $( function() {
        $('.two-digits').keyup(function(){
            if($(this).val().indexOf('.')!=-1){         
                if($(this).val().split(".")[1].length > 2){                
                    if( isNaN( parseFloat( this.value ) ) ) return;
                    this.value = parseFloat(this.value).toFixedDown(2);
                }  
             }            
             return this; //for chaining
        });
    });
    
    0 讨论(0)
提交回复
热议问题