JavaScript - Simple subtotal calculation
Asked By Vlince on 04-Feb-02 10:06 AM
This is kind of a follow-up question from my previous post but you don't need to go and read it.
I've got a simple html <table> with 4 rows <tr>...</tr>
In each row, I have a cell with a <textbox> the name of the <textbox's> are :
"txtTotal1"
"txtTotal2"
"txtTotal3"
"txtTotal4"
Now my javascript function basically loops through these 4 <textbox's> and calculates the SubTotal. Here is my javascript function:
function UpdateTotal()
{
var subtotal = 0;
for (var i=1;i<=4;i++)
{
subtotal = subtotal + eval('document.frmMain.txtTotal'+i+'.value');
}
document.frmMain.txtSousTotal.value = subtotal;
}
The problem is that it concatenates the values instead of adding them. For instance,
if my txtTotal1 = 10
and my txtTotal2 = 10.3
and my txtTotal3 = 5.3
and my txtTotal4 = 5
The end result should be = 30.6 but instead I'm getting 1010.35.35
So I then tried parsing the values using parseFloat()
subtotal = parseFloat(subtotal) + parseFloat(eval('document.frmMain.txtTotal'+i+'.value'));
I've also tried the parseFloat() inside the eval() but either way it doesn't work and I get an NaN (Not a Number) value in my txtSousTotal textbox!
What is the correct syntaxe?
Sincerely
Vlince
If I'm not mistaken...You have to convert it...
Asked By Robbe Morris on 04-Feb-02 10:20 AM
...to a number first.
var sVal ='120';
var nVal = new Number(sVal);
var nTot = 100;
alert(nTot + nVal);
Yes of course!
Asked By Vlince on 04-Feb-02 10:35 AM
This works Mr.Morris
and I thank you for it :)
Just one thing, you mention that "You have to convert it" and I tried using the parseFloat() only to realize that the parseFloat() function isn't use for casting. So is there a way, in javascript, to use casting ?
Perhaps by using your method but is there another way ?
Sincerely
Vlince
The only way I know of is to do what I did...
Asked By Robbe Morris on 04-Feb-02 10:38 AM
It works in reverse for strings
nVal = 0;
sVal = new String(nVal);
There may be another way but I don't know of one.