如何防止在html中的数字字段中插入大于最大值的值 [英] How to prevent inserting value that is greater than to max in number field in html

查看:22
本文介绍了如何防止在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.

这篇关于如何防止在html中的数字字段中插入大于最大值的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆