Getting started with Calculator project

Hey, so I’ve done some basics with this project and am starting to think about how to tackle the functionality of it.

I’m starting small: I want the display to simply show the numbers the user has entered. My page structure is as so:

            <div id="thirdRow">
                <div id="seven" class="regButton col-xs-3"> 7 </div>
                <div id="eight" class="regButton col-xs-3"> 8 </div>
                <div id="nine" class="regButton col-xs-3"> 9 </div>
                <div id="minus" class="regButton col-xs-3"> - </div>
            </div>

Then I use jquery:

    $("#one").click(function () {
        $("#math").append("7");
    });
    $("#two").click(function () {
        $("#math").append("8");
    });

Ect, ect. Thing is I’m wondering if it’s incorrect to be using separate jquery for each button. Is there a way to do this in two lines? I thought it might be possible using the .this method, but then I wasn’t sure how to print the appropriate number.

My project is hosted here for reference: http://calc.ddryburugh.com/

Thanks in advance :slight_smile:

you could try:

this.textContent

You could also change the id so that the id would be the value you want to retrieve (i.e. “7” instead of “seven”) and use this.id, but I feel that wouldn’t be good practice.

annnnother option might be a more fancy use of JS such as pushing each div into an array (document.getElementsByClassName() would do this–but be careful to note that this doesn’t return an array, but must instead be turned into an array to use any of the array prototype methods, though, a for loop would work fine). Then you could iterate over that array and add an eventlistener for each button that passes a value based on the current value of the iterator on the for loop. I’m uncertain how that would work with your existing code, though. Anyway, this.textContent should do the trick in your case.

1 Like

It depends on your overall strategy, you can have a handler for pressing each button or one for all. One for all can be something like that:

$("button").on('click', function() {
    var pressedBtn = $(this).text();
    $("#math").append("pressedBtn");
});
1 Like

Thank you both, I knew there would be a better way and you got me in the right direction!

Ok I’m struggling again with the next step which is to deal with the operation. I wanted to use an array to store the inputs, and then create a math function to work out the answer when the equals button is pressed. I’ve got the following pseudocode:

1) user enters first number --> that value is added to the current index of array
2) when operator pressed (+,-,*,/) array index increases and the operator is added to the array
3) array index increases again as a second number from the user is expected
4) user enters 2nd number
5) the output is displayed once the = button is pressed

I’m not too sure how to make this happen though. This is my javascript:

$(document).ready(function () {
    
    var value = [""];
    var i = 0;
    
    
    $(".regButton").click(function () {
        value[i] += $(this).text();
    });
    
    $("#plus").click(function () {
       i++;
        value[i] = "";
        value[i] += $(this).text();
        i++
    });
    
    //DISPLAY FOR REGULAR BTNS
    $(".regButton").click(function () {
        $("#math").append($(this).text());
    });
    //DISPLAY ZERO BTN
    $("#zero").click(function () {
        $("#math").append("0");
    });
    // CLEAR BTN
    $("#clear").click(function () {
        $("#math").html("");
    });
    $("#equal").click(function () {
        alert(value);
    })

});

If I press 8+8 the equals on my calc I expect to see an alert pop up showing 8+8, but instead it shows 8+,+,undefined8 which confuses me.

Let’s test it with the console.
Say, we have these series of actions (same as your code just without dealing with html):
var value = [""]; var i = 0; value[i] += 8; i++; value[i] = ""; value[i] += "+"; i++; value[i] += 8; console.log(value);

And it gives us…
Array [ "8", "+", NaN ]

So, we have not a number. Why? Let’s test this thing:
var arr = []; arr[0] += 8; console.log(arr);

And this gives us, as we could expect:
Array [ NaN ]

Let’s try with string (you actually have strings,not numbers, so):
var arr = []; arr[0] += '8'; console.log(arr);

And it gives us:
Array [ "undefined8" ]

Oookay. That’s where your undefined8 comes from. So, you cannot add to empty (that is, undefined) array element number or string… You actually are solving this problem in one piece of the code:
var value = [""]; var i = 0; value[i] += 8; i++; //1st increment value[i] = ""; //(!!!) value[i] += "+"; i++; //2nd increment value[i] += 8; console.log(value);
But when you increment index the second time, you don’t assign array element with such index to an empty string, so it stays undefined.

1 Like

Very helpful, you led to a big breakthrough and I got a lot further. I’m now trying to implement chaining in my equation, ie (4+4+5 should show up as 16+5) ect. My code does this much, but when I either hit = to get the result of 16+5, or use another operator nothing is happening. Could you take a quick look and see if you can spot where I’ve gone wrong with this?

$(document).ready(function () {
    var value = [""];
    var i = 0;
    $(".numberBtn, #zero").click(function () {
        value[i] += $(this).text();
    });
    $(".operatorBtn").click(function () {
        if (value.length == 3) {
            $("#math").html(eval(value[0] + value[1] + value[2]));
            var holder = eval(value[0] + value[1] + value[2]);
            value = ["",""];
            value[0] = holder;
            value[1] = $(this).text();
            i = 2;
        }
        else {
            i++;
            value[i] = "";
            value[i] += $(this).text();
            i++;
            value[i] = "";
        }
    });
    //DISPLAY FOR REGULAR BTNS
    $(".numberBtn, #zero, .operatorBtn").click(function () {
        $("#math").append($(this).text());
    });
    // CLEAR BTN
    $("#clear").click(function () {
        $("#math").html("");
        value = [""];
        i = 0;
    });
    $("#equal").click(function () {
        if (value.length == 3) {
        $("#math").html(eval(value[0] + value[1] + value[2]));
        var holder = eval(value[0] + value[1] + value[2]);
        value = [""];
        value[0] = holder;
        i = 0;
        }
        else {
            alert("Enter a complete equation!");
        }
    })
});

I got it figured out :slight_smile:

1 Like