0

I have javascript function that will calculate the value for "TOTAL" row and "Balance" column in the table. But if there are no input, the javascript will return NaN which is not a number error. How to set if there are no input in the text box, javascript will interpret it as 0 so that I will not get NaN error.

This is my table

As you can see, the textbox for pay(notes 50) column are empty. Then value for balance and total become NaN.

4
  • 1
    I guess you are probably using parseInt or equivalent somewhere. Just add an if statement to check if the String is equal to "" or not (empty string) Commented Dec 1, 2016 at 7:17
  • You can use isNan() function for checking it or you should convert the inputs to integer using parseInt(). Commented Dec 1, 2016 at 7:17
  • Or change to something like parseInt(value || 0) so that it defaults to 0 if value is not a number. Commented Dec 1, 2016 at 7:18
  • @nicovank, I've tried parseInt(value || 0) when declaring the variable and managed to parsed the value to int and set to 0 if null. Thank you so much. Commented Dec 1, 2016 at 8:56

5 Answers 5

1

just use logical 'or' operator (see short-circuit evaluation),

parseInt('10') || 0; // give 10
parseInt('') || 0; // give 0
Sign up to request clarification or add additional context in comments.

Comments

0

You can check whether the value is a number by isNaN() function and then perform summation.

Comments

0

use isNaN(), put it in an if statement, if true, set the variable to 0

if(isNaN(yourVar)) {
    yourVar = 0;
}

Comments

0

Ternary operator will work just fine

yourVar = (isNaN(yourVar)) ? 0 : yourVar

So if you want to check if your textbox value is empty or not, you can use:

val = your_textbox_value == '' ? 0 : your_textbox_value

Comments

0

assign that object to it this will work fine

you_object = you_object == null ? "0" : you_object;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.