ckportfolio.com - Basic Calculator: jQuery Pt. 3

Basic Calculator: jQuery Pt. 3

jQuery - Part 3

Now that we can confirm that the number, operator, and delete buttons work well, we need to finish the last component: computation.

Upon pressing the process button, we will want to once again declare a variable based on the display pane:

var resultOld = $("#display").val();

Here, we want to verify whether "resultOld" is an empty string or not, and display an error message if that is the case using a conditional statement:

if (resultOld == "") {
    alert("Your screen is empty. Please type in an equation.");
} else {
    // if resultOld is NOT empty..
}

When you press the process button with the display pane empty, the browser will display a popup window containing the message. Otherwise, the code will perform every task placed in "else" section of your condition statement.

Now that the first of the two possibilities has been addressed, we can move onto the actual computation component.

var resultEval = eval(resultOld);

"eval" is a JavaScript function that analyzes a given variable and tries to compute the problem contained in a variable. For instance:

  • String "2 + 4" would become 6 upon "eval"
  • "0 * 5" would become 0 upon "eval"

However, "eval" would not be able to recognize "2 + 5 5 \+" -- as the problem is an erroneous one due to the extra plus sign. This would throw an error at JavaScript level, making the application unusable. To prevent this particular situation, we need to "try" to run this eval function and "catch" any exception that may happen:

try {
    var resultEval = eval(resultOld);
    alert("The result is: " + resultEval);
} catch(ex) {
    alert("Something is wrong. Specific error: " + ex);
    $("#display").val(""); 
}

The code will initially try to run "eval" on the current display pane content, and open up a popup window containing the answer. However, if the code runs into any trouble, it will display an error message and empty the display element.

function process(){

    var resultOld = $("#display").val();

    if (resultOld == "") {
        alert("Your screen is empty. Please type in an equation.");  
    } else {

        try {    
            var resultEval = eval(resultOld);
            alert("The result is: " + resultEval);
        } catch(ex) {
            alert("Something is wrong. Error: " + ex);
            $("#display").val("");
        } 

    }

};

You should be able to see that all buttons work as intended at this point -- you just have completed a fully-functioning arithmetic calculator!

Screencast Recording

https://www.dropbox.com/scl/fi/w9x8nwyypbexsrp2w343k/Page-5.mov?rlkey=nc7rmr3hqzu0qyp7vqu1anvhp&dl=0

Fin