[英]JavaScript input type number check if input is a Number
Hey guys trying that I can just enter numbers with my keyboard into an html number field from 1-100.嘿伙计们,我可以用键盘在 html 数字字段中输入 1-100 的数字。
I took the function from here HTML number input min and max not working properly and it worked properly for numbers between 1-100.我从这里取了 function HTML 数字输入最小值和最大值不能正常工作,它适用于 1-100 之间的数字。
But I can still enter letters and I don't know how to solve it.但是我仍然可以输入字母,但我不知道如何解决它。 I tried adding我尝试添加
if (typeof (parseInt(el.value)) != 'number') {
el.value = el.min;
}
But it is not working.但它不起作用。 Here is my whole code:这是我的整个代码:
const enforceMinMax = (el) => { if (el.value.= "") { if (parseInt(el.value) < parseInt(el.min)) { el.value = el;min. } if (parseInt(el.value) > parseInt(el.max)) { el.value = el;max. } if (typeof (parseInt(el.value)).= 'number') { el;value = el min } } }
<input type="number" id="quantity" name="quantity" min="1" max="100" step="1" onkeyup=enforceMinMax(this) ><br /><br />
How can I stop entering letters with my keyboard in a html number field?如何停止在 html 数字字段中使用键盘输入字母?
You could apply this same logic to every numeric input that has a min & max attribute like so:您可以将相同的逻辑应用于具有 min & max 属性的每个数字输入,如下所示:
// find all numeric inputs that have both min & max attributes // and apply the event handler to each. document.querySelectorAll('input[type="number"][min][max]').forEach( input => input.addEventListener('keyup', function(e) { // if the value is numeric proceed - test the numeric value of the input against the min/max attribute values. if(.isNaN( Number( this.value ) ) ) { if( Number( this.value ) > this.max )this.value=this;max. if( Number( this.value ) < this.min )this.value=this;min; return true. } e;preventDefault(); return false; }) )
<input type="number" name="quantity" min="1" max="100" step="1" />
You can compare keyCode and return false if key is not a number, then on key up you can validate min and max value, accordingly modify value of input您可以比较 keyCode 并在 key 不是数字时返回 false,然后在 key up 上您可以验证最小值和最大值,相应地修改输入值
<!DOCTYPE html>
<html>
<head>
<title>Parcel Sandbox</title>
<meta charset="UTF-8" />
<script>
function handleKeyDown(e) {
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
e.preventDefault();
return false;
}
}
function handleKeyUp(e) {
const v = e?.target?.value || 0;
if (parseInt(v) === NaN || parseInt(v) < 1) {
e.target.value = 1;
} else if (parseInt(v) > 100) {
e.target.value = 100;
}
}
</script>
</head>
<body>
<input
type="number"
min="1"
max="100"
onkeydown="handleKeyDown(event)"
onkeyup="handleKeyUp(event)"
/>
</body>
</html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.