How to prevent keypress two digits after a decimal number?

谁都会走 提交于 2019-12-20 19:46:07

问题


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

$(function(){ 
    $('#name').bind('paste', function(){
    var self = this;
    setTimeout(function() {
        if(!/^[a-zA-Z]+$/.test($(self).val()))
            $(self).val('');
    }, 0);    
           }); 

        $('#salary').bind('paste', function(){
    var self = this;
    setTimeout(function() {
        if(!/^\d*(\.\d{1,2})+$/.test($(self).val()))
            $(self).val('');
    }, 0);    
           }); 

    $('.decimal').keyup(function(){
        var val = $(this).val();
        if(isNaN(val)){
             val = val.replace(/[^0-9]./g,'');


             if(val.split('.').length>2) 
                 val =val.replace(/\.+$/,"");
        }
        $(this).val(val); 
    });
    });      

My html page is

<b>Name</b>
<input type="text" id="name"  /><br/>
<b>Salary</b>
<input type="text" id="salary"  class="decimal" />

here i want only write 2 digits after decimal,how can i do this? You can see my code in http://jsfiddle.net/V6s4B/


回答1:


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.




回答2:


$("#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;
    }



回答3:


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
    });
});



回答4:


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




回答5:


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');
});


来源:https://stackoverflow.com/questions/15680506/how-to-prevent-keypress-two-digits-after-a-decimal-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!