JohnSmith
JohnSmith

Reputation: 1557

How to add html contents taken from an html table?

I have this script

$('table#preview td.price').each(function(){
var price = parseInt($(this).html());
var total;
if(price == ''){
price = 0;
}
total += price;
alert(total);
});

What it does is get the column that has the class price then supposedly adds it all up.

However, all I get from this code is NaN. I don't get what's wrong with the code.

Please note the script if(price == ''). I've done this because initially there are no contents in the table.

Edit: Here the html

    <table>
    <tr>
    <th>Name</th>
    <th>Price</th>
    </tr>
    <tr>
    <td>pen</td>
    <td class="price>6</td>
    <td>paper</td>
    <td class="price>8</td>    
    </tr>
    </table>

Upvotes: 1

Views: 1297

Answers (1)

Richard
Richard

Reputation: 8280

Try using the .text() method instead of .html() method, it should hopefully help get rid of the NaN errors. You'll want to declare the total outside the scope of each iteration so it doesn't get reset each time. Try giving this a go, I've simplified it slightly to also include a check against the number price:

var total = 0;
$('table#preview td.price').each(function()
{
    var price = parseInt($(this).text());
    if (!isNaN(price))
    {
        total += price;
    }
});

alert('The total is: ' + total);

Update

Here's a jsFiddle. N.B. .html() should also work.

Upvotes: 7

Related Questions