Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
430 views
in Technique[技术] by (71.8m points)

javascript - How to prevent inserting value that is greater than to max in number field in html

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...