Free Javascript Tutorials


JavaScript Tutorials

Variables (part three)

Our quick javascript links
Little Programmes


Adding numbers in textboxes (continued)


Whoops! Something has clearly gone wrong with our adding machine from the previous part of this javascript tutorial. Two plus two does not equal twenty two! Our programme seems to have joined our two numbers together, rather than adding them together.

The problem lies in those text boxes. Not surprisingly, what you get form a text box is text. So when we typed in the number 2, the programme thought it was text. When we told the programme to add the numbers we did it like this:

C = (A + B)

Because the programme thinks there is text in the variables A and B, it will join them together instead of adding them up. When you tried to add up 2 + 2, you got 22 and not 4. So what's the solution?

One solution is to force the programme to recognise the text as a number. We can use the JavaScript function eval(). Like this:

A = eval(document.frmOne.txtFirstNumber.value)
B = eval(document.frmOne.txtSecondNumber.value)

In other words, surround your document code with the round brackets of the eval() function. Just the first two, A and B.

Another, neater, solution is to use JavaScript's in-built Number() function:

A = document.frmOne.txtFirstNumber.value
B = document.frmOne.txtSecondNumber.value

A = Number(A)
B = Number(B)

Make sure Number has a capital "N", and not a lowercase "n". This will force JavaScript to recognize the value from a text box as a number. Using this method, however, will get you a "NaN" in the your answer text box, if your user enters a string (two + two instead of 2 + 2. NaN stands for Not a Number). So you need to do some error checking for this, which we'll get to later.

For now, pretend that your users are all well behaved, and wouldn't dream of spoiling your code by entering text instead of numbers!

When you've amended your code, try your programme again. It should work properly now.

Ok, here's a little exercise. Have a go at this.


Add a second button to your form. When this button is clicked, the two numbers in the first and second text boxes should be multiplied together. The answer should appear in the third text box. You will need to write a second function below the first one you have just wrote. When you're done, your code should work like the one below. Enter some numbers in the boxes below, then click the button to test out the scripts.

Number One: Number Two:


Right, that should have given you lots of practice with variables. Not to mention practice with getting things from text boxes on forms. We'll move on to Control Flow now. We'll use loops to turn our little programme into a "times table" calculator, and we'll use if statements to help us evaluate things.

Move on to the Next Part -->

<--Back to the JavaScript Contents Page