0

I am building a calculator. I am able to display the input value in the input field when the buttons are clicked but when the <button id="equals">

<button id="equalsButton" class="operator" value="=">=</button></td>

clicked the result value is appended instance of replacing it. For example, clicked 9, +, 9, =

Input field displays the input value: 9+918=

Input field:

<input id="display" name="display" disabled></input>

My script:

  $(document).ready(function() {
    var num1 = '';
    var num2 = '';

    var operator = '';
    var total = '';

    $('button').on('click', function(e) {
        var btn = e.target.innerHTML;

        if (btn >= '0' && btn <= '9') {
          handleNumber(btn);
          console.log('number');
        } else {
          handleOperator(btn);
          console.log('operator');
        }
    });

    function handleNumber(num) {
      if (num1 == '') {
          num1 = num;
        } else {
          num2 = num;
        }
        displayButton(num);
    }

    function handleOperator(op) {
      if (operator == '') {
          operator = op;
        } else {
          handleTotal();
          operator = op;
        }
        displayButton(op);
    }

    function handleTotal() {
        switch (operator) {
            case '+':
                total = +num1 + +num2; // Use + before variable to convert string to number
                displayButton(total);
                break;
            case '-':
                total = +num1 - +num2; // Use + before variable to convert string to number
                displayButton(total);
                break;
                ...
                ...
                ...

        }
        updateVariables();
    }

    function displayButton(btn) {
      $('#display').val($('#display').val() + btn);
    }

    function updateVariables() {
      num1 = total;
      num2 = '';
    }


      $('#clearButton').on('click', function() {
        var clear = $('#display').val('');
      });

});

This is the last issue I have. I almost finishing with the project if you see other errors beside this current question please advice and I really appreciate your help!

Thank you in advance!

passion
  • 61
  • 2
  • 9
  • [Convert a string to an integer in JavaScript?](https://stackoverflow.com/questions/1133770/convert-a-string-to-an-integer-in-javascript) – Mohamed-Yousef Feb 03 '19 at 16:51

1 Answers1

0

A solution might be a extra function for showResult and a change in handleOperator (last line) :

  $(document).ready(function() {
    var num1 = '';
    var num2 = '';

    var operator = '';
    var total = '';

    $('button').on('click', function(e) {
      var btn = e.target.innerHTML;

      if (btn >= '0' && btn <= '9') {
        handleNumber(btn);
        console.log('number');
      } else {
        handleOperator(btn);
        console.log('operator');
      }
    });

    function handleNumber(num) {
      if (num1 == '') {
        num1 = num;
      } else {
        num2 = num;
      }
      displayButton(num);
    }

      function handleOperator(op) {
      if (operator == '') {
        operator = op;
      } else {
        handleTotal();
        operator = op;
      }
      if (op != '=') { displayButton(op); }
    }

    function handleTotal() {
      switch (operator) {
        case '+':
          total = parseInt(num1) + parseInt(num2);
          showResultOnButton(total);
          break;
        case '-':
          total = parseInt(num1) - parseInt(num2);
          showResultOnButton(total);
          break;
        case '/':
          total = parseInt(num1) / parseInt(num2);
          showResultOnButton(total);
          break;
        case '*':
          total = parseInt(num1) * parseInt(num2);
          showResultOnButton(total);
          break;
      }
      updateVariables();
    }

    function displayButton(btn) {
      $('#display').val($('#display').val() + btn);
    }

    function showResultOnButton(btn) {
      $('#display').val(btn);
    }

    function updateVariables() {
      num1 = total;
      num2 = '';
    }


    $('#clearButton').on('click', function() {
      $('#display').val('');
    });

  });
nologin
  • 1,402
  • 8
  • 15
  • This returns `NaN`. – passion Feb 03 '19 at 17:04
  • yes, sthg. like '9+9' can not be converted to int. Have a look at the new solution with showResultOnButton. – nologin Feb 03 '19 at 17:15
  • It shows the first calculate result with a `=` sign behind it like this `9+9=`. Result `18=` Also if you continue using it, it will show `NaN` Link to code here. https://jsfiddle.net/krittiyaclark/v9cdont3/7/ – passion Feb 03 '19 at 17:30
  • remove the line "displayButton(op);" in handleOperator(op). displayButton makes a string concatenation! The "+" in this case does not add two numbers, it appends the second part to the first. When handleOperator adds a "="char to the number it is no number any longer, because it is a string, which can not be converted. Better initialize num1, num2 = 0 instead of '', so they are numbers. And in updateVariables set num2 = 0 instead of ''. – nologin Feb 03 '19 at 17:39
  • It does not work correctly. It seems like my script is running a bit weird. – passion Feb 03 '19 at 17:46
  • ok, handleOperator differs now if pressed '=' or not and decides to to refresh the display or not ;). The handleOperator above works in your fiddle. – nologin Feb 03 '19 at 17:56
  • I declared `var clearDisplay = false;` and it seems to work correctly (please play around and let me know if there any errors) but the `operator` does not display in the input field when the button is clicked. – passion Feb 03 '19 at 18:11
  • Yeah - it is working correctly but I do not think `var num1 = ''; var num2 = '';` have to change to `var num1 = 0; var num2 = 0;` because we use `parseInt`, correct? – passion Feb 03 '19 at 18:52
  • You don't really have to change ;) In your case it's ok handling num1 and num2 as strings. It's just not a good behavior changing the variables type during runtime. Better calculating with numbers and converting to string for viewing in display. – nologin Feb 03 '19 at 18:58