JavaScript - 只接受某些小数值

标签 javascript jquery

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

  • 最多 30
  • 最小-30
  • 点后仅 2 位数字,例如 2.25
  • 因此可能的值如下所示(2.00/2.25/2.50/2.75/3.00...)

我设法这样做了,除非最后一个条件只接受值 0.00 或 0.25 或 0.50 或 0.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/

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

最佳答案

您可以使用 % 运算符,例如 x % 0.25 == 0 ?真:假

关于JavaScript - 只接受某些小数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54305302/

相关文章:

Jquery UI 确认对话框在 fiddle 中完美显示,但不在网站上

javascript - 打开时向上滑动的下拉子菜单

javascript - 我正在尝试从最低级别组件上的输入字段捕获数据

javascript - Vuejs模板继承

javascript - 类型错误 : Cannot read property 'setState' of undefined

javascript - 如何在JS中写CSS?

javascript - 使用 jquery 调整宽度,使 p 元素高 4 行

javascript - jQuery数字库转换时总是返回0

javascript - webview 无法加载 index.html

javascript - 如何使用API​​ V3获取chanel封面?