-1

Im beginner at JS and I have stucked on this problem. I have tried and read on google and other people with almost same issue but I cant make this work.

 var start = 0;
 // Add number
var total = document.getElementById('div1').innerHTML += start;
document.getElementById('divResult').innerHTML = total;

That code is in a button click function. The value start at 0. And every time press the button, the value from div1 is + in divResult.

so if div1 contain the value 10 then divResult should be +10 every time button is pressed. The value in div1 is dynamic.

Now that code just do "101001010010" Just keeps adding 1 and 0 when press the button.

hollowman
  • 1
  • 1
  • 1
    `var total = document.getElementById('div1').innerHTML += start;` what this line is doing? – brk Sep 23 '19 at 10:19
  • total = value of div1 + start and start is 0 – hollowman Sep 23 '19 at 10:21
  • something + 0 = something – Yannick K Sep 23 '19 at 10:22
  • Hey @hollowman, try to edit the post making the code functional to let you show the changes proposed easily. – Lionel T Sep 23 '19 at 10:22
  • parse the initial value within the div then sum and instert `var total = parseInt(document.getElementById('div1').text) + start; document.getElementById('divResult').innerHTML = total;` – Sim1-81 Sep 23 '19 at 10:23
  • Slim, that code gave me "NaN" as result. – hollowman Sep 23 '19 at 10:32
  • `

    10

    Result

    `
    – Jijo Robin Sep 23 '19 at 10:38

1 Answers1

-1

You have to wrap the innerHTML into Number() or parseInt() depending on your case.

Here you have a post could help understand better how to convert strings into Numbers in JavaScript.

Lionel T
  • 1,559
  • 1
  • 13
  • 30