使用类型=“数字”的输入来区分NaN输入和空输入。 [英] Differentiate between NaN input and empty input with an Input of type="number"

查看:147
本文介绍了使用类型=“数字”的输入来区分NaN输入和空输入。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用type =number的表单输入,只允许输入数字。

 < input type =numberclass =form-control fc-input/> 

我没有提交按钮,而是在输入失去焦点后检查值。但是,当使用type =number并输入非数字时, valueAsNumber 属性的输入将是无用的(NaN和)。问题在于我想区分用户输入空字符串()和用户输入非数字值(例如123abc)。当输入为空时,我想执行函数a,如果它只是一个非数字,我想执行函数b(否则执行c)。



是否有一种区分NaN输入和空()输入的好方法?

解决方案

问题是输入类型的数字在封面下面有很多东西,并且它的规范不会向您公开实际的无效值。所以一个空输入和一个无效字符串看起来是一样的。因此,您需要使用有效性



var result = document.getElementById (result); document.getElementById(num)。addEventListener(keyup,function(){var isValid = this.validity.valid; var len = this.value.length; if(isValid&& ();} len){result.innerHTML =No value;} else if(!isValid){result.innerHTML =Invalid number;} else {result.innerHTML =Valid number:+ this.valueAsNumber;}}) ;

< input type =numberid = />< span id =result>< / span>

上述代码的问题在于如果您需要,空检查将失败。如果需要,if检查将需要

  if(!isValid&& this.validity.valueMissing){ 


I want to use a form input with type="number" and only allow numbers to be entered.

<input type="number" class="form-control fc-input"/>

I don't have a submit button, instead the value is checked after the input loses focus. However when you use type="number" and a non-number is entered, both the valueAsNumber and the value attributes of the input will be useless (NaN respectively ""). The problem with this is that I want to differentiate between the user entering an empty string (""), and the user entering a non-number value (e.g. 123abc). When the input is empty I want to execute function a, and if it's just a non-number I want to execute function b (otherwise do c).

Is there a good way to differentiate between NaN input and empty ("") input like this?

解决方案

The problem is input type of number does a lot of stuff under the covers and the specification for it does not expose the actual invalid value to you. So an empty input and an invalid string look the same. So you need to do some investigation work using validity

var result = document.getElementById("result");

document.getElementById("num").addEventListener("keyup", function() {
  var isValid = this.validity.valid;
  var len = this.value.length;

  if (isValid && !len) {
      result.innerHTML = "No value";
  } else if (!isValid) {
      result.innerHTML = "Invalid number";
  } else {
      result.innerHTML = "Valid number: " + this.valueAsNumber;
  }

});

<input type="number" id="num" />
<span id="result"></span>

Problem with the code above is if you make it required, the empty check will fail. If it is required the if check would need to be

if (!isValid && this.validity.valueMissing) {

这篇关于使用类型=“数字”的输入来区分NaN输入和空输入。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆