【发布时间】: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