Getting a integer value from a textbox, how to che

2020-03-02 03:11发布

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)?

4条回答
姐就是有狂的资本
2楼-- · 2020-03-02 03:30

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);
}
查看更多
等我变得足够好
3楼-- · 2020-03-02 03:30

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.

查看更多
Viruses.
4楼-- · 2020-03-02 03:35

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;
}
查看更多
smile是对你的礼貌
5楼-- · 2020-03-02 03:44

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.

查看更多
登录 后发表回答