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?

1
  • Start using jQuery. It easy and fast to learn Commented May 12, 2017 at 0:36

2 Answers 2

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>

Sign up to request clarification or add additional context in comments.

Comments

0

just edit the variables x1 and x2 into:

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

5 Comments

Thanx It worked
This leaves the web page open to cross-site scripting attacks. Imagine if someone gave value1 an input of <img src="xxx" onerror="doSomethingEvil()" />. You also need to check that the input is a valid number.
Thanx, but I just needed to edit my code to work it and this solved it. My task is very small one so I need only a few code.
Is this code on a publicly viewable website? If so, you need to secure it, or you are putting your users at risk.
No this is just for testing purpose. I'll add validation methods later :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.