简体   繁体   English

如何防止在十进制数后按下两位数?

[英]How to prevent keypress two digits after a decimal number?

I have got a task to prevent keypress two digits after a decimal number.我有一个任务来防止在十进制数后按下两位数。 My jquery file is我的 jquery 文件是

$(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我的 html 页面是

<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?这里我只想在小数点后写 2 位数字,我该怎么做? You can see my code in http://jsfiddle.net/V6s4B/你可以在http://jsfiddle.net/V6s4B/看到我的代码

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.您可以前处理的关键事件keyupkeypress ,如果输入的是不是我们喜欢,我们可以从发生禁用事件。 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 js小提琴

$('.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 js小提琴

$('.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.请注意,如果newValue包含的数字超过 2 个小数位,则parseFloat(newValue) * 100 % 1 > 0计算结果为 true。

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

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

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.我混合了这个人的答案,来自https://stackoverflow.com/a/10514166/5382523 的@Tats_innit 和上面的 @Rick Calder。

EDIT also from this guy, isJustMe from https://stackoverflow.com/a/17289322 for the parseFloat with "|| 0".编辑也来自这个人,来自https://stackoverflow.com/a/17289322 的isJustMe 用于带有“|| 0”的 parseFloat。 Because if the input's field is null or zero "NaN" is shown and you can't delete it.因为如果输入的字段为空或零,则会显示“NaN”并且您无法删除它。

HTML HTML

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

JAVASCRIPT (JQUERY) 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) (y)

More info about toFixed - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed有关 toFixed 的更多信息 - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed

I did it this way: Provided a class allow-only-numbers, for your input then:我是这样做的:提供了一个类allow-only-numbers,供您输入:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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