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