-1

i want to add the numeric values from the given table. the alert box should display the sum.

<html>
    <head>
    <script type="text/javascript">
function Calc()
{
i=0
temp=0;
ab=0;
while(i<=5)
{
ab=document.getElementById("tabl").rows[0].cells[i].innerHTML;
temp+=ab;
i++
}
    alert(temp);
}
    </script>
    </head>
    <body>
<table id="tabl" border="1">
            <tr>
        <td>01</td>
            <td>02</td>
        <td>03</td>
            <td>04</td>
        <td>05</td>
            <td>06</td>
        </tr>
    </table>
<input type="button" value="Calculate" onclick="Calc()"> 
    </body>
    </html>

however on executing the program the alert box displays 010203040506.

2 Answers2

1

Use

temp+=parseFloat(ab);

Or parseInt() if they are always integers.

Otherwise you just concatenate the string, while you need to convert it to numbers to perform addition.

n-dru
  • 9,285
  • 2
  • 29
  • 42
0

You're concatenating string values, not adding numbers, use parseFloat or parseInt in your equation.

See it working here: http://jsfiddle.net/7N6vX/

sellmeadog
  • 7,437
  • 1
  • 31
  • 45