Positive to Negative
I can't drive Tip 55...
There's one more thing to worry about in this here calculator script and that is the button that changes numbers from negative to positive. Remember in the first Tip in this series we saw two text boxes and one was hidden? Now that all comes into play.
Let's take a final look at it all.
(It's big. Get it all.)
Three codes will come into play here. The first is the button that triggers the function that changes a number from positive to negative or back again. It has the value of +|- on the front and the code looks like this:
<INPUT TYPE=BUTTON VALUE=" +|- " NAME="sign" onClick="change()">
Let's take a look at what happens. When the button is clicked, the value that appears in the display (document.calculator.text.value) is assigned the variable name "temp".
Next, the script tests to see if the value is already negative. An If statement asks if the text.substring's first character is equal to the minus sign. Remember that any time you set a substring, you have to set up a comparison where the larger number wins. In this case the two numbers are 0 and 1. The one is bigger, thus it wins and the first character in the substring is checked.
Notice the two equal signs. That means "is equal to."
If the first character is equal to the minus sign, the hidden text box comes into play. Here's that code:
So, back to If The First Character Is The Minus Sign. If it is, then the hidden text box is given a value of nothing. By doing that it brings it into play. That hidden box is then set to 0, the value in the display is taken away, and the result is timed by 1. That sets the same number to a positive value.
If the first character is not a minus sign, the second If statement comes into play. This statement asks if the first character is NOT equal to a minus sign. (!= is the operator for "is not equal to").
If this If statement is true, then, again, the hidden box is given a value of nothing to bring it into play. The value of the hidden box is then set to a minus sign plus the full length of the "temp" variable substring.
I know that seems a bit much, but by adding the value through a substring, the value remains the same. Rather than the entire thing being seen as one entity, which it is not, it remains a string of characters, which it is.
And that wraps up the calculator. It was quite involved and sometimes a little rough to get hold of, but now that you're through it, I think you'll agree it was a doable project.