我有以下html5输入元素:
<input type="number">
为什么这个输入允许在输入字段中输入字符“e”?无法输入其他字母字符(如预期的那样)
使用chrome v. 44.0.2403.107
下面的例子来看看我的意思。
= >“当家”型输入<
我有以下html5输入元素:
<input type="number">
为什么这个输入允许在输入字段中输入字符“e”?无法输入其他字母字符(如预期的那样)
使用chrome v. 44.0.2403.107
下面的例子来看看我的意思。
= >“当家”型输入<
当前回答
使用angular,你可以限制输入e,+,-, e
<input type="number" (keypress)="numericOnly($event)"/>
numericOnly(event): boolean { // restrict e,+,-,E characters in input type number
debugger
const charCode = (event.which) ? event.which : event.keyCode;
if (charCode == 101 || charCode == 69 || charCode == 45 || charCode == 43) {
return false;
}
return true;
}
其他回答
<input type="number" onkeydown="return FilterInput(event)" onpaste="handlePaste(event)" >
function FilterInput(event) {
var keyCode = ('which' in event) ? event.which : event.keyCode;
isNotWanted = (keyCode == 69 || keyCode == 101);
return !isNotWanted;
};
function handlePaste (e) {
var clipboardData, pastedData;
// Get pasted data via clipboard API
clipboardData = e.clipboardData || window.clipboardData;
pastedData = clipboardData.getData('Text').toUpperCase();
if(pastedData.indexOf('E')>-1) {
//alert('found an E');
e.stopPropagation();
e.preventDefault();
}
};
上述解决方案只适用于普通html。 对于reactJS,我建议你这样做
<input type="number" onKeyDown={(e) =>["e", "E", "+", "-"].includes(e.key) && e.preventDefault()} >
角;与IDE keyCode弃用警告
功能上与rinku的答案相同,但有IDE警告预防
numericOnly(event): boolean {
// noinspection JSDeprecatedSymbols
const charCode = (event.which) ? event.which : event.key || event.keyCode; // keyCode is deprecated but needed for some browsers
return !(charCode === 101 || charCode === 69 || charCode === 45 || charCode === 43);
}
简单而标准的解决方案:在Angular/ Js/ Ts中,你可以使用正则表达式来限制任何输入键。
HTML: <input type=“text” name=“input1” (keypress)=“numericOnly($event)” />
TS:
numericPattern = /^[0-9]*$/;
numericOnly(event){
return this.numericPattern.test(event.key);
}
因为这正是规范所规定的。数字输入可以接受浮点数,包括负号和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".