Javascript-仅接受小数的确定值 [英] Javascript - Accepting only certains values for decimals

查看:57
本文介绍了Javascript-仅接受小数的确定值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数字字段需要使用纯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/

控制应该在键盘上.这就是为什么我不能使用诸如min/max/step之类的html5属性的原因.

解决方案

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步的数字.

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

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

  • 注意:上次编辑没有什么额外的改进.

JS小提琴(我不知道如何将其嵌入答案中)

I have a number field to wich I need to apply certain conditions with pure JS or jQuery:

  • Max 30
  • Min -30
  • Only 2 digits after the point, example 2.25
  • So possible values are like this (2.00 / 2.25 / 2.50/ 2.75 / 3.00...)

I managed to do so unless for the last condition that should accept only values .00 or .25 or .50 or .75 Here is my code:

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/

[EDIT] Control should be on keyup. This is why I can't use html5 attributes like min/max/step...

解决方案

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

This will allow only numbers with 0.25 steps.

Digit-only algorithm has been improved to completely prevent other type of input to be displayed (your code shows the forbidden input and then erases it).

This is the basic idea, a lot of other improvements can be made. For example, to always show two decimals (EX. 2.00 instead of 2), make an animation, etc. Currently, the check is set to happen after focus ends.

  • NOTE: Little extra improvements made in last edit.

JS Fiddle (I don't know how to embed it to the answer)

这篇关于Javascript-仅接受小数的确定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆