We help IT Professionals succeed at work.
Get Started

Error NaN when trying to add two input fields in Javascript

kenjpete
kenjpete asked
on
162 Views
Last Modified: 2015-10-12
I am trying to sum two text fields using Javascript and my result keeps coming back as NaN (not a number?) and I am entering only numbers in the input fields. Despite some debugging in Visual Studio, I still can't figure out why?

Here is my HTML code:

<div id="calc">
        <p>
            <label for="num1">Enter Your First Number:</label>
            <input type="text" name="txtNum1" id="txtNum1" size="5" />
        </p>

        <p>
            <label for="num1">Enter Your Second Number:</label>
            <input type="text" name="txtNum2" id="txtNum2" size="5" />
        </p>

        <input type="button" name="add" id="add" value="Add" onclick="addNum();" />
       

    </div>

        <div id="ShowResults"></div>

Open in new window


And here is my javascript:
var firstNumber = parseInt(document.getElementById('txtNum1').value);
var secondNumber = parseInt(document.getElementById('txtNum2').value);

function addNum() {

        var result = firstNumber + secondNumber;

            resultMessage = "Your answer is: " + result;
            ShowResults.innerHTML = resultMessage;

}

Open in new window


Any help would be appreciated!
Comment
Watch Question
CERTIFIED EXPERT
Most Valuable Expert 2013
Awarded 2012
Commented:
This problem has been solved!
Unlock 2 Answers and 2 Comments.
See Answers
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE