Welcome to the second part of a six-part series on how to build a calculator for your web page. In the previous part, we got into the basics of setting up the calculator's layout and what functions we want it to have. In this part, we will begin to code the functions.
Coding a Web Page Calculator - Code Basics (Page 2 of 5 )
From the user’s requirements we develop the code basics. Of course, from the basics we shall develop the details.
When the web page opens, you do not see the calculator. When you click the “Use Calculator” button, the function showCalc() is called. This function displays the calculator. We saw this function in the previous part of the series. This function should do any initialization of the calculator. One of the things to do at initialization is to give the value of zero to the Input Text Control. So the following line should be added to the function showCalc():
document.getElementById('CI1').value = "0";
CI1 is the ID of the Input Text Control, which is the display.
Two Main Standard Calculator Functions
Look at the picture of the standard calculator again and then read through the user's requirements above. You will notice that the function (or functions) called when you click the digit buttons, is (are) of a different nature to the one (ones) called when you click the non-digit buttons. When you click a digit button, the digit should appear on the calculator display; if there was already a number (or digit) on the display, the new digit should appear next to it on the right. However, when you click a non-digit button, some operation (e.g. + or clear display) should be carried out.
I actually have two functions: one that responds to the digits and another that responds to non-digits. The one that responds to the digits is showNum(); the one that responds to the non-digits is operator(). Well, there is an exception here. The decimal point button, the +/- button and the RM button call the showNum() function and not the operator() function. Their tasks are better handled by the showNum() function than the operator() function, as we shall see.