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

后端 未结 4 1325
我寻月下人不归
我寻月下人不归 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:12

    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.

提交回复
热议问题