2

I have two HTML input elements. I need to get an output by add those input values together. I created a JavaScript function to do that but, the output is "NaN" always.

HTML:

<input type="text" id="value1" /> <br/>
<input type="text" id="value2" /> <br/>
<button id="button1" onclick="calc()">Calculate</button>
<p id="result"></p>

JavaScript:

function calc()
{
    var x1 = document.getElementById('value1');
    var x2 = document.getElementById('value2');
    var r = x1+x2;
    document.getElementById('result').innerHTML=r;
}

How do I get the real output here?

2 Answers2

3

You need to get the value attribute of the input. document.getElementById returns a reference to the input itself. Also, avoid using the onclick attribute, it is better to separate the logic from the HTML with addEventListener.

This code uses parseInt to convert the value from the inputs to a number. You could also use parseFloat. The isNaN check ensures both submitted values are numeric. isNaN returns true if the value it tests is not a number.

document.getElementById("button1").addEventListener("click", function(evt) {
      var x1 = parseInt(document.getElementById('value1').value);
      var x2 = parseInt(document.getElementById('value2').value);
      if (isNaN(x1) || isNaN(x2)) {
        alert('Both values must be numeric');
      } else {
        document.getElementById('result').textContent = x1 + x2;
      }
    });
<input type="text" id="value1" /> <br/>
<input type="text" id="value2" /> <br/>
<button id="button1">Calculate</button>
<p id="result"></p>
user2182349
  • 9,569
  • 3
  • 29
  • 41
0

just edit the variables x1 and x2 into:

var x1 = document.getElementById('value1').value;
var x2 = document.getElementById('value2').value;