views:

2619

answers:

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

A: 

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.

TheTXI
+1, I use the very same regex, and it works fine.
karim79
That's actually modified slightly for this answer. If you check the revision history you'll see that the original piece of code was to check for decimal values. I had to modify it to work for ints :P
TheTXI
+5  A: 

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);
}
Tor Haugen
A: 

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.

fforw
A: 

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;
}
Ben Lowery