Reputation: 7
Good morning, all. So, I have 4 text boxes that are being summed and the total displayed in 1 text box. I'm getting a total, but it's doing more than addition and giving me the wrong total value. I'm not sure why, unless it is parsing incorrectly. Any help would be much appreciated. I've attached a screenshot of what it is doing as well as my code below. You can see with this picture the total is incorrect
Thanks to you all,
<script type="text/javascript">
function myFunction()
{
var v1 = form1.txtCu2Row.value;
var v2 = form1.txtCu3Row.value;
var v3 = v1 + v2
var v4 = form1.txtCu4Row.value;
var v5 = form1.txtCu5Row.value;
var v6 = v4 + v5
form1.txtTotalCuAB.value = parseInt(v3) + parseInt(v5) ;
}
Upvotes: 0
Views: 56
Reputation: 87292
The parseInt
is necessary when read from for example an input as the value you get is a string representation of the number, and as such you can't calculate with it.
As soon as you parsed it, the variable will be an integer, which can be used for calculations, hence it works as expected.
Do like this.
function myFunction()
{
var v1 = parseInt(form1.txtCu2Row.value);
var v2 = parseInt(form1.txtCu3Row.value);
var v3 = v1 + v2
var v4 = parseInt(form1.txtCu4Row.value);
var v5 = parseInt(form1.txtCu5Row.value);
var v6 = v4 + v5
form1.txtTotalCuAB.value = v3 + v6;
}
And if you don't need all those variables, like this maybe.
function myFunction()
{
var v2 = parseInt(form1.txtCu2Row.value);
var v3 = parseInt(form1.txtCu3Row.value);
var v4 = parseInt(form1.txtCu4Row.value);
var v5 = parseInt(form1.txtCu5Row.value);
form1.txtTotalCuAB.value = v2 + v3 + v4 + v5;
}
Upvotes: 2