将文本输入限制为四分之一小数增量

问题描述 投票:0回答:2

我正在尝试找到一种方法将文本输入限制为数字和四分之一小数增量。例如 0.25、.5、2.75、4.0、10.5 等。基本上是整数 0-9,然后是小数 0、.25、.5、.75。我试图将它建立在

的基础上
<script>
jQuery('.numbersOnly').keyup(function () {
    this.value = this.value.replace(/[^0-9\.]/g,'');
});
</script>

这将输入限制为十进制数,但无法真正弄清楚如何限制为四分之一小数增量,如上所示。有什么想法吗?

javascript jquery html forms
2个回答
4
投票
  1. 使用小数位数让用户写入最多 2 位小数的数字
  2. 使用
    e.KeyCode == 8
    取消退格键上的更改
  3. 如果数字不正确,请使用模糊事件来输入正确的数字

    function decimalPlaces(num) {
       var match = (''+num).match(/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/);
       if (!match) { return 0; }
       return Math.max(
         0,
         // Number of digits right of decimal point.
         (match[1] ? match[1].length : 0)
         // Adjust for scientific notation.
         - (match[2] ? +match[2] : 0));
    }
    
    jQuery('.numbersOnly').keyup(function (e) {
         this.value = this.value.replace(/[^0-9\.]/g,'');
         if(e.keyCode == 8 || decimalPlaces(this.value) < 2){
            return true;
         }
         else if(this.value % 1 != 0)
             this.value = (Math.round(this.value * 4) / 4).toFixed(2);
    
    });
    jQuery('.numbersOnly').on('blur',function () {
         if(this.value % 1 != 0)
            this.value = (Math.round(this.value * 4) / 4).toFixed(2);
    });
    

一个正在工作的小提琴


2
投票

这可以通过 html 元素的属性来完成,而不需要任何其他 javascript。

© www.soinside.com 2019 - 2024. All rights reserved.