1

I'm trying to calculate the user's input but when I'm trying to do a quick addition it outputs NaN= instead of the actual result

The user should be able to click the buttons to do the math, the problem is that my code can't get the user input before the user did the math

e.g. = User input: 1+4; My code can't get the 1 or the 4 and can't do math

Here is what I tried:

Code snippet :

var buttons = document.getElementsByClassName("buttons")[0];

 buttons.onclick = (element) => {
  if (element.target.className != "buttons") {
   if (element.target.innerHTML == "=") {
    for (var i = 0; i < result.innerHTML.length; i++) {
     if (buttons.innerHTML = "+") {
      result.innerHTML = element.target.value + i; 
     }
    }
   }
   result.innerHTML += element.target.innerHTML;
   console.log("User: " + element.target.innerHTML);
  }
 }
  <div class="result">
          </div>
          <div class="buttons">
            <div>&larr;</div>
            <div>C</div>
            <div>%</div>
            <div>/</div>
            <div>7</div>
            <div>8</div>
            <div>9</div>
            <div>x</div>
            <div>4</div>
            <div>5</div>
            <div>6</div>
            <div>-</div>
            <div>1</div>
            <div>2</div>
            <div>3</div>
            <div>+</div>
            <div>0</div>
            <div>.</div>
            <div class="equal">=</div>
          </div>

 

I can't edit the HTML and use jQuery.

Nikola Lukic
  • 4,001
  • 6
  • 44
  • 75
  • I don't think it's a duplicate since my numbers doesn't have any variables – Tobias Rieper Jun 13 '18 at 07:53
  • your "numbers" are actually strings.. you need to parse them with: parseInt("your value", 10) – Margon Jun 13 '18 at 08:02
  • Why are you using divs? Form controls actually have calculation features baked in. I'd like to know in what circumstance you'd be in that you can't change a bunch of divs. BTW "numbers don't have variables"? Ok, I wasn't aware that they ever could but vice versa certainly. Do not be afraid of `var` it is your friend. – zer00ne Jun 13 '18 at 08:15

1 Answers1

0

So the problem here is that when you add the text contained in an element to the text contained in some other element the result is not a number NaN. Hmmm, well last I checked doing math on strings does not produce numbers. Maybe we should try some of javascript's string parsing functions that are designed to produce numbers? parseInt

parseInt(result.innerHTML, 10) += parseInt(element.target.innerHTML);
gforce301
  • 2,944
  • 1
  • 19
  • 24