将数字输入限制到范围 [英] Limit number input to range
问题描述
我想将用户输入限制为特定范围(-90到90).数字可以是整数或十进制.默认值必须为0
.我不不想使用HTML5 min
/max
属性.
I want to limit a user input to a specific range (-90 to 90). Number can be integer or decimal. The default value must be 0
. I do not want to use HTML5 min
/ max
attributes.
这是我的HTML:
<input type="number" value="0" />
这是我尝试过的:
$('input').on('input', function () {
var value = $(this).val();
$(this).val(Math.max(Math.min(value, 90), -90));
});
这是有问题的,因为它不允许我擦除默认值(因此,我不能为负数输入-
或为十进制数输入.
).
This is buggy because it doesn't let me erase the default value (therefore I cannot enter a -
for a negative number or a .
for a decimal number).
所以我最终这样做了:
$('input').on('input', function () {
var value = $(this).val();
if ((value !== '') && (value.indexOf('.') === -1)) {
$(this).val(Math.max(Math.min(value, 90), -90));
}
});
那更好,但是现在的问题是我可以输入超出定义范围的90.1
.
That's better, but now the problem is that I can enter 90.1
which is out of my defined range.
建议?
推荐答案
仅考虑 修改超出范围的值.这使您可以包含小数等.
Consider only modifying the value when it's out of range. This lets you include decimals, etc.
$('input').on('input', function () {
var value = this.value;
if (value !== '') {
value = parseFloat(value);
if (value < -90)
this.value = -90;
else if (value > 90)
this.value = 90;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" value="0" />
这篇关于将数字输入限制到范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!