Calculate the sum of products using the td attribute

I have this table:

<table> <thead> <tr> <th>Quantity</th> <th>&nbsp;</th> <th>Price</th> <th>Sum</th> </tr></thead> <tbody> <tr class="sum"> <td><input class="qty" type="text" value="1" /></td> <td>German format: </td> <td data_price="1375.5">1.375,50 &euro;</td> <td></td> </tr> <tr class="sum"> <td><input class="qty" type="text" value="1" /></td> <td>English format:</td> <td data_price="1375.5">&euro;1,375.50</td> <td></td> </tr> <tr class="sum"> <td><input name="text" type="text" class="qty" value="1" /></td> <td>French format:</td> <td data_price="1375.5">1 375,50 &euro;</td> <td></td> </tr> <tr class="sum"> <td><input name="text2" type="text" class="qty" value="1" /></td> <td>Italian format:</td> <td data_price="1375.5">&euro;1,375.50</td> <td></td> </tr> <tr class="sum"> <td><input class="qty" type="text" value="1" /></td> <td>Spanish format:</td> <td data_price="1375.5">&euro; 1.375,50</td> <td></td> </tr> <tr> <td colspan="3">Total</td> <td id="total"></td> </tr> </tbody> </table> 

and I want to use the value of the "data_price" attribute to calculate the SUM, as in this link: http://jsfiddle.net/QmTNZ/77/

I want to use only the "data_price" attribute in the calculation, not.

Please help, I'm still new to jquery :)

+6
source share
3 answers

For your price cells, you should use this format:

 <td data-price="1375.5">&euro;1,375.50</td> 

i.e. with a hyphen rather than an underscore

Then you can use:

 $('td').data('price') 

to access its value - see http://api.jquery.com/data

eg.

 var sum = 0; $('.sum').each(function() { var q = parseFloat($(this).find('.qty').val()); var p = parseFloat($(this).find('td').eq(2).data('price')); sum += q * p; }); $('#total').text(sum); 

Working demo at http://jsfiddle.net/alnitak/gzYhN/

+6
source

Try

 var sum=0; $('tbody > tr > td[data_price]').each( function() { sum += parseFloat(this.attr('data_price')); } ); 
0
source

Try the following: http://jsfiddle.net/ptfKJ/

This example uses the HTML source code.

0
source

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


All Articles