gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 23:22:44 24 4
gpt4 key购买 nike

我正在尝试找到一种方法来将文本输入限制为数字和四分之一小数增量。例如 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>

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

最佳答案

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

工作fiddle

关于javascript - 将文本输入限制为四分之一小数增量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37649505/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com