【问题标题】:Function works with text input but not numerical input函数适用于文本输入,但不适用于数字输入
【发布时间】:2015-12-02 11:02:14
【问题描述】:

我有一个 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。

【问题讨论】:

  • htlm5 数字输入(顾名思义)意味着只接受数值。它将忽略任何非数字字符,而不会更改目前输入的值。如果您希望在输入字母时清除输入(假设您有充分的理由想要这种行为),您必须从文本输入开始并监听关键事件。 stackoverflow.com/questions/4416505/…(和你一样)

标签: javascript html function input nan


【解决方案1】:

数字输入不允许非数字数据,所以这总是错误的:

truth= isNaN(value);

相反,您可以检查按下的键是数字还是小数:

input=document.getElementById('inf');
input.onkeyup=function(e) {
  if(!/[\d\.]/.test(String.fromCharCode(e.which))) {
    input.value='';
  }
};
&lt;input type='number' id='inf'/&gt;

【讨论】:

    【解决方案2】:

    输入类型为数字时,如果文本中有非数字字符则返回null。
    所以

    "abc123" = ""  
    "123abc" = ""  
    "123" = "123"  
    
    
    isNaN(null) is false.
    

    【讨论】:

      【解决方案3】:

      您可以只检查blank 以及您的isNaN 检查

      var truth = isNaN(value) || value==='';

      由于输入 type=number 会将任何非数字转换为空白

      【讨论】:

        猜你喜欢
        • 2011-06-08
        • 1970-01-01
        • 1970-01-01
        • 2020-01-31
        • 2014-12-14
        • 1970-01-01
        • 2023-04-05
        • 2019-11-15
        • 1970-01-01
        相关资源
        最近更新 更多