Function Details for a Web Page Calculator - The Second Code Segment
(Page 3 of 5 )
The second code segment is a switch statement. Each case in the switch statement corresponds to a digit button, the +/- button, the decimal point button or the RM button. The first case is:
case "B0":
valueAlreadyThere = document.getElementById('CI1').value;
valueAlreadyThere+="0";
if (!(/^00/.test(valueAlreadyThere)))
document.getElementById('CI1').value = valueAlreadyThere;
break;
Clicking the zero digit button corresponds to this case. When any digit button is clicked, the digit joins any number that was already on the display, to the right. So the first line here gets any number that was on the display into the local variable string, named valueAlreadyThere. The second line adds the character zero to the variable.
Next, we have an “if” statement. We do not want any number beginning with more than one zero. So the “if” statement verifies, using the regular expression technique, whether the content of the variable which is to go to the display is “00.” If it is, it allows only one zero on the display. If it is not, it means zero will be added to the digit or number that was on the display. The “if” statement does this by writing the content of the valueAlreadyThere string variable back to the display.
The second case is:
case "B1":
valueAlreadyThere = document.getElementById('CI1').value;
valueAlreadyThere+="1";
document.getElementById('CI1').value = valueAlreadyThere;
break;
case "B2":
This case corresponds to the digit button of 1. The first line reads the content of the display and assigns it to the valueAlreadyThere string local variable. The character 1 is appended to the string content of valueAlreadyThere in the second line. The last line writes the content of valueAlreadyThere to the display. In this way, one is added to the right of any number that was on the display. If there was no number on the display, 1 becomes the only number on the display.
The next case in our second code segment is:
case "B2":
valueAlreadyThere = document.getElementById('CI1').value;
valueAlreadyThere+="2";
document.getElementById('CI1').value = valueAlreadyThere;
break;
This case corresponds to the digit button of 2. The explanation is similar to the previous case.
Next: Second Code Segment continued >>
More HTML Articles
More By Chrysanthus Forcha