Weird Issue with JS calculator

Weird Issue with JS calculator
0

#1

Hi everyone,

I started working on the JS calculator today and I am running into a weird issue.

you can find the codepen here:

https://codepen.io/heenslice/pen/YxOdaM?editors=0010

I am currently attempting to to console.log the correct answers before displaying results to the screen.

My current issue is regarding this section.

// display numbers (first number)
$('.number').click(function(){
  var $buttonValue = $(this).text();
  totalString1 = totalString1 + $buttonValue;
  console.log(totalString1);
  return totalString1;
});

// apply operator
$('.operator').click(function(){
  $('.btn').addClass('number2');
  $('.btn').removeClass('number');
  if($(this).text() === '+'){
    console.log('add');
  }
});

// display numbers (second number)
$('.number2').click(function(){
  console.log('2nd function');
  var $buttonValue = $(this).text();
  totalString2 = totalString2 + $buttonValue;
  console.log(totalString2);
  return totalString2;
});

My logic is that after you create the first string and click on ‘+’. It will remove the number class. and add the number2 class. So the next time you click a number we will start creating the second string.

However, even after removing the number class. When I click a number it still fires the first function. Am I missing something really obvious?

Any help/advice would be much appreciated


#2

I reviewed your Codepen. When I click on an operator, the “number” classe is removed and the “number2” class is added to all elements with a class of “btn”. Have you resolved the problem you asked about in your original post?


#3

Yeah, I managed to work around the above issue by using the following:

// display numbers (first number)
$('.number').click(function(){
  var $buttonValue = $(this).text();
  if($('.btn').hasClass('number')){
    totalString1 = totalString1 + $buttonValue;
    console.log('string1', totalString1);
    $('.display').text(totalString1);
    return totalString1;
  } else if($('.btn').hasClass('number2')){
    totalString2 = totalString2 + $buttonValue;
    console.log('string2', totalString2);
    $('.display').text(totalString2);
    return totalString2;
  }
});

This ensured the second function would fire after clicking an operator button. I’m still not sure why the original code didn’t work


#4

I would not want to speculate why it did not work with the small bit of code you showed in the post, because there could have been other code (which is no longer present) which could have been causing trouble.


#5

Fair enough. Thanks anyway!