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

后端 未结 4 1316
我寻月下人不归
我寻月下人不归 2021-01-05 06:46

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.

4条回答
  •  一向
    一向 (楼主)
    2021-01-05 07:15

    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);
    }
    

提交回复
热议问题