How to add html content taken from 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 he does is get a column with the price of the class, and then, presumably, everything will add it.

However, all I get from this code is NaN. I do not understand what is wrong with the code.

Pay attention to the script if (price == '') . I did this because initially there is no content in the table.

Edit: here is 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> 
+1
source share
1 answer

Try using the .text() method instead of the .html() method, it will hopefully help get rid of NaN errors. You need to declare total outside the scope of each iteration, so it does not get reset every time. Try to give this, I simplified it a bit to include checking for 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 is jsFiddle . Notabene .html() should also work.

+7
source

Source: https://habr.com/ru/post/916933/


All Articles