How do I enter HTML values correctly in Javascript?
I have two HTML input elements. I need to get the result by adding these input values together. I created a JavaScript function to do this, 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?
+3
source to share
2 answers
You need to get the attribute value . 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 using addEventListener .
This code uses parseInt to convert the value from the inputs to a number. You can also use parseFloat . The isNaN check ensures that both presented values are numeric. isNaN returns true if the value it is testing 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>
+3
source to share