Getting a integer value from a textbox, how to check if it's NaN or null etc?

Getting a integer value from a textbox, how to check if it's NaN or null etc?

清晨说晚安 发布于 2021-11-26 字数 232 浏览 674 回复 4 原文

I am pulling a value via JavaScript from a textbox. If the textbox is empty, it returns NaN. I want to return an empty string if it's null, empty, etc.

What check do I do? if(NAN = tb.value)?

如果你对这篇文章有疑问,欢迎到本站 社区 发帖提问或使用手Q扫描下方二维码加群参与讨论,获取更多帮助。

扫码加入群聊

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

携君以终年 2022-06-07 4 楼

One thing you could do is a regex check on the value of the textbox and make sure it fits the format of an accepted number, and then if it fits the format perform your process, otherwise return an empty string.

Edit: This is an example from some code I have in front of me (might not be the best regular expression):

var anum=/(^d+$)/;

if (!anum.test(document.getElementById("<%=txtConceptOrderValue.ClientID %>").value))
{
    alert("Order Value must be a valid integer");
    document.getElementById("<%=txtConceptOrderValue.ClientID %>").focus();
    return false;
}

Edit 2: I should also note that I am using ASP.NET which is why I have the slightly funky way of accessing the textbox. In your regular JavaScript case it may not be as cluttered.

梦一生花开无言 2022-06-07 3 楼

Assuming you have a reference to the input text box:

function getInteger(input) {
  if(!input || !input.value) return "";

  var val = parseInt(input.value, 10);

  if(isNaN(val)) return "";
  else return val;
}
高跟鞋的旋律 2022-06-07 2 楼

You can also do it this way:

var number = +input.value;
if (input.value === "" || number != number)
{
    // not a number
}

NaN is equal to nothing, not even itself.

if you don't like to use + to convert from String to Number, use the normal parseInt, but remember to always give a base

var number = parseInt(input.value, 10)

otherwise "08" becomes 0 because Javascript thinks it's an octal number.

望她远 2022-06-07 1 楼

Hm, something is fishy here.

In what browser does an empty textbox return NaN? I've never seen that happen, and I cannot reproduce it.

The value of a text box is, in fact a string. An empty text box returns an empty string!

Oh, and to check if something is NaN, you should use:

if (isNaN(tb.value))
{
   ...
}

Note: The isNaN()-function returns true for anything that cannot be parsed as a number, except for empty strings. That means it's a good check for numeric input (much easier than regexes):

if (tb.value != "" && !isNaN(tb.value))
{
   // It's a number
   numValue = parseFloat(tb.value);
}