如何防止在html中的数字字段中插入大于最大值的值

2022-01-17 00:00:00 numbers field forms javascript html

我在html5中使用数字字段,

这是我的代码,

我使用 javascript 设置了这个数字字段的最大值.

element.max = 数量;元素.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 = 最大值;}}

<input type="number" class="edit-items" max='10'/>

希望这会有所帮助.

I am using number field in html5,

here is my code,

<input type="number" class="edit-items" />

i set the max of this number field using javascript.

element.max = quantity;
element.min = 0;
element.step = 1;

If i am using the arrow-up in the number field. Greater value than the max is not possible. But when I tried to insert in the field, greater value than the max is possible.

I would like to prevent it. How?

解决方案

Like you said input of type number will work fine with arrows and not with manual change so try to use oninput event to help you control user inputs :

    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'/>

Hope this helps.

相关文章