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

社会主义新天地 提交于 2019-11-28 06:03:08

问题


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?


回答1:


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.




回答2:


Add an event listner on the input (oninput) : check it here : 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();


来源:https://stackoverflow.com/questions/34577806/how-to-prevent-inserting-value-that-is-greater-than-to-max-in-number-field-in-ht

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!