函数适用于文本输入但不适用于数字输入
Function works with text input but not numerical input
我有一个 JavaScript 函数,可以在输入字母字符时清除文本输入。
input = document.getElementById('inf');
input.onkeyup = function() {
value = input.value;
truth = isNaN(value);
if (truth) {
input.value = '';
}
};
input {
border: 2px solid black;
margin-right: 10px;
}
<input type='text' id='inf' />Numbers Only
<br />Type a number in, and it stays. Put a letter in, and the input clears itself
问题是,当输入类型设置为数字时,这不起作用,如下例所示。
input=document.getElementById('inf');
input.onkeyup=function(){
value=input.value;
truth=isNaN(value);
if(truth){
input.value='';
}
};
input{
border:2px solid black;
}
<input type='number' id='inf'/>
<br />
As you can see, it doesnt work anymore.
我的问题是双重的:
1) 为什么它适用于文本输入而不适用于数字输入?
2)有简单的解决方法吗?我需要它作为数字输入,所以它必须保持不变。
请Javascript 只回答。没有jQuery。
数字输入不允许非数字数据,因此这将始终为 false:
truth= isNaN(value);
相反,您可以检查按下的键是数字还是小数:
input=document.getElementById('inf');
input.onkeyup=function(e) {
if(!/[\d\.]/.test(String.fromCharCode(e.which))) {
input.value='';
}
};
<input type='number' id='inf'/>
当输入类型为数字时,returns如果文本中有非数字字符则为空
所以
"abc123" = ""
"123abc" = ""
"123" = "123"
isNaN(null) is false.
您可以在检查 isNaN
的同时检查 blank
var truth = isNaN(value) || value==='';
因为输入 type=number 会将任何非数字转换为空白
我有一个 JavaScript 函数,可以在输入字母字符时清除文本输入。
input = document.getElementById('inf');
input.onkeyup = function() {
value = input.value;
truth = isNaN(value);
if (truth) {
input.value = '';
}
};
input {
border: 2px solid black;
margin-right: 10px;
}
<input type='text' id='inf' />Numbers Only
<br />Type a number in, and it stays. Put a letter in, and the input clears itself
问题是,当输入类型设置为数字时,这不起作用,如下例所示。
input=document.getElementById('inf');
input.onkeyup=function(){
value=input.value;
truth=isNaN(value);
if(truth){
input.value='';
}
};
input{
border:2px solid black;
}
<input type='number' id='inf'/>
<br />
As you can see, it doesnt work anymore.
我的问题是双重的:
1) 为什么它适用于文本输入而不适用于数字输入?
2)有简单的解决方法吗?我需要它作为数字输入,所以它必须保持不变。
请Javascript 只回答。没有jQuery。
数字输入不允许非数字数据,因此这将始终为 false:
truth= isNaN(value);
相反,您可以检查按下的键是数字还是小数:
input=document.getElementById('inf');
input.onkeyup=function(e) {
if(!/[\d\.]/.test(String.fromCharCode(e.which))) {
input.value='';
}
};
<input type='number' id='inf'/>
当输入类型为数字时,returns如果文本中有非数字字符则为空
所以
"abc123" = ""
"123abc" = ""
"123" = "123"
isNaN(null) is false.
您可以在检查 isNaN
的同时检查 blank
var truth = isNaN(value) || value==='';
因为输入 type=number 会将任何非数字转换为空白