简体   繁体   English

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

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

I am using number field in html5,我在 html5 中使用数字字段,

here is my code,这是我的代码,

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

i set the max of this number field using javascript.我使用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 :就像你说的,输入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'/>

Hope this helps.希望这可以帮助。

Add an event listner on the input (oninput) : check it here : on change sample在输入 (oninput) 上添加事件侦听器:此处检查:更改示例

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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何防止插入值大于用户在文本字段中输入的数字 - How to prevent inserting value greater than the number which user enters in text field 防止用户在输入字段中输入大于2位数字的值 - Prevent users from entering a value greater than 2 digits in an input field 如何在html文本字段中限制数字的最大值和最小值 - How to limit the max and min value of number in html text field HTML5:使用键盘输入,类型为“数字”的输入字段仍将接受比其“最大值”更高的值 - HTML5 : Input field with the type of 'number' will still accept higher value than its 'max' using keyboard inputs 如何防止输入字段接受大于最大值的值 - How to prevent input field from accepting values grater than max value 如何防止手动更改大于max-date的日期为uib-datepicker - How to prevent from manually changing the date greater than max-date for uib-datepicker 如何在 ECMAScript 中检查数字是否大于 Number.MAX_SAFE_INTEGER - How to check if number greater than Number.MAX_SAFE_INTEGER in ECMAScript javascript测试值是否为数字和大于0的数字 - javascript testing if a value is a number AND a number greater than 0 验证输入字段的值大于另一个 - Verifying that the value of a input field is greater than another 检查数组的和是否大于最大数,反之亦然 - checking if sum of array is greater than max number and vice versa javascript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM