0

I try to implement the following simple equation (5+x=?) using html and JavaScript:

function count() {
  var x = document.getElementById("myInput").value;
  document.getElementById('execute').innerHTML = x + 5;
}
<div> 5 + <input type="number" id="myInput">
  <input type="button" value="=" onclick="count()">
  <span id="execute">?</span>
</div>

Unfortunately when I write for example 2 in the input field and then click on the button (=) it gives me as answer the number 52, instead of the answer that I would like to see – 7.

It seems that it just joins the new number next to 5, instead of adding it, like it is a string and not a number. I know it’s not the brightest function and it’s not very useful, but I will appreciate if you could give me a hint where I am wrong.

This will help me understand better JavaScript and continue my education.

Narendra Jadhav
  • 10,052
  • 15
  • 33
  • 44
DimitarM
  • 151
  • 7

2 Answers2

1

I hope this will help. Thank you.

    function count()
    {var x = document.getElementById("myInput").value;
        document.getElementById('execute').innerHTML = parseInt(x) + 5;}
<div> 5 + <input type="number" id="myInput">
    <input type="button" value="=" onclick="count()">
    <span id="execute">?</span>
    </div>  
Alexis
  • 816
  • 2
  • 11
  • 28
-2

Several ways to change a string to a number, for this example I use parseInt() with 10 for the radix.

function count() {
  var x = document.getElementById("myInput").value;
  var xn = parseInt(x,10);
  document.getElementById('execute').innerHTML = xn + 5;
}
<div> 5 + <input type="number" id="myInput">
  <input type="button" value="=" onclick="count()">
  <span id="execute">?</span>
</div>
Mark Schultheiss
  • 32,614
  • 12
  • 69
  • 100