Learn how to program a calculator with jQuery.
Jennifer Bland
Previously, I showed you how to use CSS border-radius property to create the following calculator. Now I will show you how to use jQuery to implement the functionality of the calculator.
caption id="attachment_1319" align="alignnone" width="436"
Calculator using the CSS border-radius feature/caption
At the bottom of my index.html file, I will add the following script tag:
<script src=”https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
A number button would correspond to the numbers 0–9. All other buttons are operators.
2 + 3 = 5
Likewise, a user can enter this much longer sequence:
2 + 3 * 4 / 5 - 6 = -2
To improve on this, we can simplify things to only need four global variables:
A logical question would be what do you do with the third or fourth number that a user enters? The simple answer is that we reuse num1 and num2.
Once the total has been calculated, we can replace the value in num1 with the total. We would then need to empty out the operator and num2 variables. Let’s walk through this with our second example from above:
2 + 3 * 4 / 5 - 6 = -2 // num1 is assigned value of 2 // operator is assigned value of + // num2 is assigned value of 3 // total is assigned the value of 5 // num1 is assigned the value of 5 // num2 and operator are cleared // operator is assigned value of * // num2 is assigned value of 4 // total is assigned value of 20 // num1 is assigned value of 20 // num2 and operator are cleared // operator is stored value of / // num2 is assigned value of 5 // total is assigned value of 4 // num1 is assigned value of 4 // num2 and operator are cleared // operator is assigned value of - // num2 is assigned value of 6 // total is assigned value of -2 // num1 is assigned value of -2 // num2 and operator are cleared // operator is assigned value of =
The first step is to get the key that a user pressed. Here is a snippet of my index.html file that shows all the buttons on one row of the calculator:
<div class="flex-row"> <button class="calc-btn">1</button> <button class="calc-btn">2</button> <button class="calc-btn">3</button> <button class="calc-btn">+</button> </div>
<button></button>
In jQuery, you can have a button click function. When a button is clicked, the function is passed an event object. The
event.target
innerHTML
Here is the code that will console.log the button that a user clicks.
<script> $(document).ready(function() { $('button').on('click', function(e) { console.log('e', e.target.innerHTML); }); }); </script>
let num1 = ''; let num2 = ''; let operator = ''; let total = '';
function handleNumber(num) { // code goes here } function handleOperator(oper) { // code goes here }
Here is my initial step to test to make sure I can tell which button was clicked:
$(document).ready(function() { $('button').on('click', function(e) { let btn = e.target.innerHTML; if (btn >= '0' && btn <= '9') { console.log('number'); } else { console.log('operator'); } }); });
$(document).ready(function() { $('button').on('click', function(e) { let btn = e.target.innerHTML; if (btn >= '0' && btn <= '9') { handleNumber(btn); } else { handleOperator(btn); } }); });
Here is what my handleNumber function looks like:
function handleNumber(num) { if (num1 === '') { num1 = num; } else { num2 = num; } }
Here is what my handleOperator function looks like:
function handleOperator(oper) { operator = oper; }
In our index.html file, we have a div with a class of 'calc-result-input' that displays our input. We will use this to display numbers to our users.
Since we have separated out our calculator activity into functions, we will create a function to display the button.
Here is what my displayButton function looks like:
function displayButton(btn) { $('.calc-result-input').text(btn); }
Here is what my handleNumber function looks like now:
function handleNumber(num) { if (num1 === '') { num1 = num; } else { num2 = num; } displayButton(num); }
For example, if the user enters:
2 + 3 =
If the user enters:
2 - 1 =
We create a "handleTotal" function to handle this. This function will create a total based on the operator pressed. Since there are multiple operators that can be pressed, we will use a case statement to handle them.
For simplicity’s sake, I am only going to show the code to handle when the user clicks the + operator button.
Here is the handleTotal function:
function handleTotal() { switch (operator) { case '+': total = +num1 + +num2; displayButton(total); break; } }
total = +num1 + +num2;
To handle this we will need to make a change to our existing handleOperator function. Previously, we were assigning the operator variable the value of the operator button the user clicked. Now we need to know if this is the first operator the user has clicked or not. We don’t calculate a total when the user clicks on the first operator.
To account for this, we can check to see if the operator variable has a value of ''. If so, this is the first operator. If operator has a value, then we will want to calculate a total.
Here is what the handleOperator() function looks like now:
function handleOperator(oper) { if (operator === '') { operator = oper; } else { handleTotal(); operator = oper; } }
I copy the entire contents of the script tag into this file. I delete the opening script tag and closing script tag in my index.html file.
The last thing we need to do is to tell our index.html file where our scripts are. We do this by adding this line below the script tag that loads jQuery at the bottom of the index.html file:
<script src="app.js"></script>
The style.css is used to style my calculator. Please review my previous article that talks about using the CSS border-radius property to style the calculator.
The app.js file contains the logic behind the calculator.
Here is what my app.js file looks like:
let num1 = ''; let num2 = ''; let operator = ''; let total = ''; $(document).ready(function() { $('button').on('click', function(e) { let btn = e.target.innerHTML; if (btn >= '0' && btn <= '9') { handleNumber(btn); } else { handleOperator(btn); } }); }); function handleNumber(num) { if (num1 === '') { num1 = num; } else { num2 = num; } displayButton(num); } function handleOperator(oper) { if (operator === '') { operator = oper; } else { handleTotal(); operator = oper; } } function handleTotal() { switch (operator) { case '+': total = +num1 + +num2; displayButton(total); break; case '-': total = +num1 - +num2; displayButton(total); break; case '/': total = +num1 / +num2; displayButton(total); break; case 'X': total = +num1 * +num2; displayButton(total); break; } updateVariables(); } function displayButton(btn) { $('.calc-result-input').text(btn); } function updateVariables() { num1 = total; num2 = ''; }