javascript - 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/
[编辑] 控制应该在 keyup 上。这就是为什么我不能使用像 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 步长的数字。
仅数字算法已得到改进,以完全防止显示其他类型的输入(您的代码显示禁止输入,然后将其删除)。
这是基本思想,可以进行很多其他改进。例如,始终显示两位小数(EX. 2.00 而不是 2)、制作动画等。目前,检查设置为在焦点结束后进行。
- 注意:在上次编辑中做了一些额外的改进。
JS Fiddle(我不知道如何将它嵌入到答案中)
推荐阅读
- python-3.x - Selenium FileUpload accept() 没有点击按钮
- angular - 角度6:使按钮工作以显示数据
- angular - 处理来自后端 API 的错误并以 Angular 6 前端形式显示它们
- c - 在 Linux 上使用 ALSA 库
- windows - 通过命令提示符的 Python 程序不允许 > 或 < 作为输入
- spring-boot - Springboot Ehcache 加载数据
- apache-flink - Flink Web UI:如何从 flink Web UI 中删除“取消”按钮
- python - Keras 模型从数小时内预测体验
- python - 如何使用 Keras/Tensorflow 在两点获得渐变
- java - 在 AnchorPane JavaFX 中的窗格中缩放节点