Error NaN when trying to add two input fields in Javascript

kenjpete
kenjpete used Ask the Experts™
on
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

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Rikin ShahMicrosoft Dynamics CRM Consultant
Commented:
Hi,

put the initialization part into the function you have defined. And it should work.

function addNum() {

var firstNumber = parseInt(document.getElementById('txtNum1').value);
var secondNumber = parseInt(document.getElementById('txtNum2').value);

        var result = firstNumber + secondNumber;

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

}

Open in new window

Most Valuable Expert 2013
Awarded 2012
Commented:
Hi,
you should move the variables inside the function, otherwise they will be set too early in the process:
function addNum() {

var firstNumber = parseInt(document.getElementById('txtNum1').value);
var secondNumber = parseInt(document.getElementById('txtNum2').value);

        var result = firstNumber + secondNumber;

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

}

Open in new window


HTH
Rainer

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial