我想将数字类型的 html5 输入字段限制在 1-999.99 范围内。我尝试了这个,但由于某种原因它不起作用。
<input id="amount" class="formField" type="number" step="any" style="width:100%" min="1" max="999.99" />
但还要注意,我在网上发现了以下 JavaScript 代码,这些代码也在同一个字段上运行,旨在给人一种 atm 入口的感觉。
$(function() {
var input = ""; //holds current input as a string
$("#amount").keydown(function (e) {
//handle backspace key
if (e.keyCode == 8 && input.length > 0) {
input = input.slice(0, input.length - 1); //remove last digit
$(this).val(formatNumber(input));
}
else {
var key = getKeyValue(e.keyCode);
if (key) {
input += key; //add actual digit to the input string
$(this).val(formatNumber(input)); //format input string and set the input box value to it
}
}
return false;
});
function getKeyValue(keyCode) {
if (keyCode > 57) { //also check for numpad keys
keyCode -= 48;
}
if (keyCode >= 48 && keyCode <= 57) {
return String.fromCharCode(keyCode);
}
}
function formatNumber(input) {
if (isNaN(parseFloat(input))) {
return "0.00"; //if the input is invalid just set the value to 0.00
}
var num = parseFloat(input);
return (num / 100).toFixed(2); //move the decimal up to places return a X.00 format
}
});
我希望 html5 能立即解决问题,但也许它与 javascript 存在某种冲突?我对 javascript 不太了解。
最佳答案
HTML5 输入最大值和最小值不限制键盘输入,您可以检查模糊事件中的值,例如:
<input id="amount" class="formField" type="number" step="0.01" style="width:100%" min="1" max="999.99" onblur="validate(this);" />
代码:
function validate(obj)
{
if(obj.value<1 || obj.value>999.99)
{
alert("You have invalid input. Correct it!");
obj.focus();
}
}
关于javascript - 按长度或数值限制文本字段输入值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32669312/