首页 > 解决方案 > Javascript - 只接受小数的某些值

问题描述

我有一个数字字段,我需要使用纯 JS 或 jQuery 应用某些条件:

我设法这样做了,除非最后一个条件应该只接受值 .00 或 .25 或 .50 或 .75 这是我的代码:

var t_myField   = false;
var myField_min = -30;
var myField_max = 30;
$('#myField').focus(function ()
{
    var $this = $(this)
    t_myField = setInterval(
        function ()
        {
            if (($this.val() < myField_min || $this.val() > myField_max) && $this.val().length != 0)
            {
                if ($this.val() < myField_min)
                {
                    $this.val(myField_min)
                }
                if ($this.val() > myField_max)
                {
                    $this.val(myField_max)
                }
            }
        }, 50)
});

$('#myField').on("keyup", function (e)
{
    // Replacer , by .
    $(this).val($(this).val().replace(/,/g, '.'));

    // Allow only float numeric values (positif & negatif)
    var self = $(this);
    self.val(self.val().replace(/[^0-9\.-]/g, ''));
    if (e.which != 46 && e.which != 45 && e.which != 46 && !(e.which >= 48 && e.which <= 57))
    {
        e.preventDefault();
    }

    // Allow max 2 digits after decimals for certain fields
    match      = (/(\d{0,2})[^.]*((?:\.\d{0,2})?)/g).exec(this.value.replace(/[^\d.]/g, ''));
    this.value = match[1] + match[2];
});
<input type="text" name="myField" id="myField" class="myField">

JSFIDDLE => https://jsfiddle.net/Cartha/vq65Lypj/5/

[编辑] 控制应该在 keyup 上。这就是为什么我不能使用像 min/max/step 这样的 html5 属性...

标签: javascriptjquery

解决方案


let myField = document.getElementById('myField');

myField.addEventListener('keypress', onlyNumbers,{passive: false});
myField.addEventListener('change', checkInput);

function onlyNumbers(e) {
    if (!isNumberKey(e)) {
        e.preventDefault();
    }
}

function isNumberKey(e) {
    return (e.which <= 31 || (e.which >= 48 && e.which <= 57) || e.which === 45 || e.which === 46);
}

function checkInput(e) {
    let x = parseFloat(e.target.value);
    if (!isNaN(x)) {
      if (x > 30) {
        x = 30;
      } else if (x < -30) {
        x = -30;
      } else if (x % 0.25 !== 0) {
        x = Math.round(x / 0.25) * 0.25;
      }
      e.target.value = x.toFixed(2);
    }
}

这将只允许具有 0.25 步长的数字。

仅数字算法已得到改进,以完全防止显示其他类型的输入(您的代码显示禁止输入,然后将其删除)。

这是基本思想,可以进行很多其他改进。例如,始终显示两位小数(EX. 2.00 而不是 2)、制作动画等。目前,检查设置为在焦点结束后进行。

  • 注意:在上次编辑中做了一些额外的改进。

JS Fiddle(我不知道如何将它嵌入到答案中)


推荐阅读