【问题标题】:Javascript - Accepting only certains values for decimalsJavascript - 只接受小数的某些值
【发布时间】:2019-01-22 09:42:00
【问题描述】:

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

  • 最多 30 个
  • 最小 -30
  • 点后只有 2 位数字,例如 2.25
  • 所以可能的值是这样的 (2.00 / 2.25 / 2.50/ 2.75 / 3.00...)

我设法做到了,除非最后一个条件应该只接受值 .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 属性...

【问题讨论】:

  • Step by 0.25 表示您想在特定事件上将文本框的值增加 0.25?
  • 听起来范围输入可能更适合您的需求。
  • 我的意思是:在该点之后没有可能的值比这些:nothing or .00 or .25 or .50 or .75
  • 请重新检查我的答案。 Web 组件使这变得非常容易和可读。将input type="number"input 事件上的一些 Javascript 检查和值替换相结合在这里做得很好。
  • @RoryMcCrossan 一个定制的内置input type="number" 我想说这是最好的方法。看我的回答。

标签: javascript jquery


【解决方案1】:

您可以使用% 运算符,如x % 0.25 == 0 ? true : false

【讨论】:

  • 不知道为什么这被否决了。 OP 的问题可能不清楚,但据我所知,这可以正确验证该步骤。
  • 您能否解释更多或更好,给出完整的答案? JSF 中?谢谢:)
  • @Cartha 帮助您入门,使用的运算符称为模运算符(% 符号)。查看here 以快速了解它的作用。
【解决方案2】:
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(不知道怎么嵌入到答案中)

【讨论】:

  • 赞成。这是一个好的开始。是的,可以进行很多改进:)
  • 我刚刚编辑了我的最后一个答案,为您添加了一些改进。看看这个。它应该是您正在寻找的。​​span>
【解决方案3】:

我建议在这里创建一个 Web 组件。我将向您展示自定义内置组件的基本设置,该组件已经工作并且不涉及摸索$(document).ready()DOMContentLoaded

class DecimalInput extends HTMLInputElement {
  constructor() {
    super();
    this.addEventListener('input', (e) => {
      const val = parseFloat(this.value),
        min = parseFloat(this.min),
        max = parseFloat(this.max),
        step = parseFloat(this.step);
        
      if (val%step !== 0) {
        this.value = Math.round(val/step) * step
      }
      if (val > max) {
        this.value = max
      }
      if (val < min) {
        this.value = min
      }
      
      this.value = Number(this.value).toFixed(2, 10);
    })
  }
}

customElements.define('decimal-input', DecimalInput, { extends: 'input' })
&lt;input type="number" is="decimal-input" min="-30" max="30" step="0.25" value="0" /&gt;

这个组件已经非常接近您的要求了。使用它在此基础上进行我们自己的改进。

【讨论】:

  • 此代码接受高于 30 的值(尝试 30.5),不将数字限制为点后 2,并接受点后所需的任何值。
  • 代码有一些错误,我现在修复了。我的回答只能作为一个起点,展示如何使用 Web 组件解决问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多