Page 141 - KEC Khaitan C5 Flipbook
P. 141

C. Add Event Listeners for Operators:

                   o    Store the current input and operator, then reset for the next input:

                     onEvent("btnPlus", "click", function() {
                       previousInput = currentInput;

                       operator = "+";
                       currentInput = "";

                       setText("display", "");
                    });

                     // Repeat for -, *, /
                   D. Implement the Equals Button:

                   o   Calculate and display the result:

                     onEvent("btnEquals", "click", function() {
                       var result = 0;
                       if (operator == "+") {

                         result = parseFloat(previousInput) + parseFloat(currentInput);
                       } else if (operator == "-") {

                         result = parseFloat(previousInput) - parseFloat(currentInput);
                       } else if (operator == "*") {

                         result = parseFloat(previousInput) * parseFloat(currentInput);
                       } else if (operator == "/") {
                         if (currentInput != "0") {

                           result = parseFloat(previousInput) / parseFloat(currentInput);
                         } else {

                           result = "Error";  // Division by zero check
                         }

                       }
                       setText("display", result);
                       currentInput = result.toString();

                       operator = "";
                       previousInput = "";

                    });
                   E. Add a Clear Button:

                   o   Reset the display and all variables:

                     onEvent("btnClear", "click", function() {




                                                                          Working with Variables and Conditional Logic  139
   136   137   138   139   140   141   142   143   144   145   146