Reputation: 41
I am a new learner of Java Script. I'm having a problem with my mathematical equation. Its showing wrong answer. please help me to find the mistake.
<html>
<head>
<title>calculation of (p+r)*(n+r) </title>
<script>
function calculate()
{
var p = document.getElementById("p").value;
var n = document.getElementById("n").value;
var r = document.getElementById("r").value;
var calculationa= p+r;
var calculationb= n+r;
var cal_final=Number(calculationa)*Number(calculationb);
document.getElementById("result").innerHTML=cal_final;
}
</script>
</head>
<body>
<h1>calculation of (p+r)*(n+r)</h1>
p: <input id="p"><br/>
n: <input id="n"><br/>
r: <input id="r"><br/>
<button onclick="calculate()">calculate</button>
<p id="result"></p>
</body>
</html>
It is the equation I want to solve. The math shows this result which is not correct.https://i.sstatic.net/Ir9hs.png
How can i fix this ?
Upvotes: 2
Views: 121
Reputation: 506
Also can try this .....
function calculate()
{
var p= Number(document.getElementsByName("p")[0].value);
var n= Number(document.getElementsByName("n")[0].value);
var r= Number(document.getElementsByName("r")[0].value);
var sum1 = p+ r;
var sum2 = n+ r;
var res=sum1 *sum2;
document.getElementsByName("result1")[0].value = res;
}
<h1>calculation of (p+r)*(n+r)</h1>
p: <input type="text" name="p"><br/>
n: <input type="text" name="n"><br/>
r: <input type="text" name="r"><br/>
<br/>
<input type="button" name="add" value ="add" onClick="calculate()" />
result: <input type="text" name="result1"><br/>
Upvotes: 1
Reputation: 4148
In Javascript var value considering as string.
For integer value addition used parseInt().
For Floating value addition used parseFloat().
Please check this for more information http://www.tutorialspoint.com/java/java_numbers.htm
function calculate()
{
var p = document.getElementById("p").value;
var n = document.getElementById("n").value;
var r = document.getElementById("r").value;
var calculationa= parseInt(p)+parseInt(r);
var calculationb= parseInt(n)+parseInt(r);
var cal_final=parseInt(calculationa)*parseInt(calculationb);
document.getElementById("result").innerHTML=cal_final;
}
Upvotes: 0
Reputation: 3356
The values are assigned to p
, n
and r
as strings. So, p+r = 1+2 = 12
.
Use parseInt()
to parse the values as Integer and do calculations. Or use parseFloat()
function calculate() {
var p = parseInt(document.getElementById("p").value);
var n = parseInt(document.getElementById("n").value);
var r = parseInt(document.getElementById("r").value);
var calculationa= p+r;
var calculationb= n+r;
var cal_final=Number(calculationa)*Number(calculationb);
document.getElementById("result").innerHTML=cal_final;
}
<h1>calculation of (p+r)*(n+r)</h1>
p: <input id="p"><br/>
n: <input id="n"><br/>
r: <input id="r"><br/>
<button onclick="calculate()">calculate</button>
<p id="result"></p>
Upvotes: 2