Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

JQuery Calculator

Hi Guys,

I have recently set myself the challenge of creating a calculator to expand my knowledge on JQuery. I'm stuck at the moment. I have looked at some examples on Codepen and I can't seem to understand their approach to using operators to calculate from within the display. I do understand at some point that I will have to replace x & ÷ to * & / (times & divide) as they aren't recognised in programming in that format.

Could someone please give me guidance on how I should approach this? I'm just kind of lost at the moment. Somewhere to start would be of help, like areas to learn etc.

Here is my codepen: https://codepen.io/Nathan-Callum-Marshall/pen/BxMWaG?editors=1111

Thanks,

1 Answer

Steven Parker
Steven Parker
243,199 Points

Your pen code currently just displays strings representing the pushed buttons, but to perform the actual calculations, you'll need to convert the strings into numbers and then apply the correct operators.

Here's a few hints and suggestions:

  • use a different class for operators
  • as values are entered, create a numeric value (register)
  • when an operator is entered, store the operation to perform later and save the numeric value
  • when the equal is entered, perform the operation on the two numeric values
  • the convention of $ in variable names is for jQuery objects, not values

An example of building up the numeric value in the button handler:

register = register * 10 + parseInt(valueHTML);  // variable was "$valueHTML"

And when handling an operator:

operator = valueHTML;
operand = register;
register = 0;

And when handling equals:

switch(operator) {
  case "+": total = operand + register; break;
  case "-": total = operand - register; break;
  // ...etc.
}

Sorry for the late Thank you Steven. ? This answer really made me realise that I should go and learn JavaScript from cratch to understand the math fundamentals.