我有以下html5输入元素:
<input type="number">
为什么这个输入允许在输入字段中输入字符“e”?无法输入其他字母字符(如预期的那样)
使用chrome v. 44.0.2403.107
下面的例子来看看我的意思。
= >“当家”型输入<
我有以下html5输入元素:
<input type="number">
为什么这个输入允许在输入字段中输入字符“e”?无法输入其他字母字符(如预期的那样)
使用chrome v. 44.0.2403.107
下面的例子来看看我的意思。
= >“当家”型输入<
当前回答
一个简单的解决方案,排除除整数
<输入 类型=“数字” min=“1” 步骤=“1” onkeypress=“return event.keyCode === 8 ||事件.字符代码 >= 48 &&; 事件.字符代码 <= 57“>
此解决方案不防止复制和粘贴(包括字母“e”)。
其他回答
因为这正是规范所规定的。数字输入可以接受浮点数,包括负号和e或e字符(其中指数是e或e后面的数字):
A floating-point number consists of the following parts, in exactly the following order: Optionally, the first character may be a "-" character. One or more characters in the range "0—9". Optionally, the following parts, in exactly the following order: a "." character one or more characters in the range "0—9" Optionally, the following parts, in exactly the following order: a "e" character or "E" character optionally, a "-" character or "+" character One or more characters in the range "0—9".
要隐藏字母e和负号,可以这样做:
onkeydown="return event.keyCode !== 69 && event.keyCode !== 189"
最简单的解决方案是parseInt()。
<input type="number" onkeyup="this.value = parseInt(this.value); this.paste(this.onkeyup);"/>
ParseInt()对于E, E, +, -和任何不是数字的东西返回空白(NaN)。
使用onkeyup和keydown根据您的方便与粘贴事件。对我来说,onkeyup工作最好。这也适用于复制粘贴
<input type="number" onkeydown="javascript: return ['Backspace','Delete','ArrowLeft','ArrowRight'].includes(event.code) ?isNaN(Number(event.key)) && event.code!= =‘空间’" / >
简单而标准的解决方案:在Angular/ Js/ Ts中,你可以使用正则表达式来限制任何输入键。
HTML: <input type=“text” name=“input1” (keypress)=“numericOnly($event)” />
TS:
numericPattern = /^[0-9]*$/;
numericOnly(event){
return this.numericPattern.test(event.key);
}