如何防止在 html 的数字字段中插入大于最大值的值
How to prevent inserting value that is greater than to max in number field in html
我在 html5、
中使用数字字段
这是我的代码,
<input type="number" class="edit-items" />
我使用 javascript 设置此数字字段的最大值。
element.max = quantity;
element.min = 0;
element.step = 1;
如果我在数字字段中使用向上箭头。大于最大值的值是不可能的。但是当我尝试在字段中插入时,可能会出现比最大值更大的值。
我想阻止它。怎么样?
就像你说的 number
类型的输入可以很好地使用箭头而不是手动更改所以尝试使用 oninput
事件来帮助你控制用户输入:
document.getElementsByClassName('edit-items')[0].oninput = function () {
var max = parseInt(this.max);
if (parseInt(this.value) > max) {
this.value = max;
}
}
<input type="number" class="edit-items" max='10'/>
希望对您有所帮助。
在输入 (oninput) 上添加一个事件侦听器:
在这里查看:on change sample
function maxValue(){
var numbers = document.getElementById("numbers");
console.log(numbers);
var maxQuantity = 5;
numbers.addEventListener("input", function(e) {
if(this.value>maxQuantity) {
alert("max value reached ! ");
this.value = maxQuantity;
}
})
};
window.onload = maxValue();
我在 html5、
中使用数字字段这是我的代码,
<input type="number" class="edit-items" />
我使用 javascript 设置此数字字段的最大值。
element.max = quantity;
element.min = 0;
element.step = 1;
如果我在数字字段中使用向上箭头。大于最大值的值是不可能的。但是当我尝试在字段中插入时,可能会出现比最大值更大的值。
我想阻止它。怎么样?
就像你说的 number
类型的输入可以很好地使用箭头而不是手动更改所以尝试使用 oninput
事件来帮助你控制用户输入:
document.getElementsByClassName('edit-items')[0].oninput = function () {
var max = parseInt(this.max);
if (parseInt(this.value) > max) {
this.value = max;
}
}
<input type="number" class="edit-items" max='10'/>
希望对您有所帮助。
在输入 (oninput) 上添加一个事件侦听器: 在这里查看:on change sample
function maxValue(){
var numbers = document.getElementById("numbers");
console.log(numbers);
var maxQuantity = 5;
numbers.addEventListener("input", function(e) {
if(this.value>maxQuantity) {
alert("max value reached ! ");
this.value = maxQuantity;
}
})
};
window.onload = maxValue();