|
Free
Javascript
Tutorials
|
|
|
JavaScript Tutorials Variables (part three) |
||||||||||||||||||||||
|
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) 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 A = Number(A) 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.
|