Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate the sum of products using a 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 attribute "data_price" to calculate the SUM like in this link : http://jsfiddle.net/QmTNZ/77/

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

Please help, I'm still beginner in jquery :)

like image 846
Ahmed Ala Dali Avatar asked Jul 18 '11 09:07

Ahmed Ala Dali


1 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, not underscore

You can then use:

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

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

e.g.

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/

like image 76
Alnitak Avatar answered Oct 23 '22 05:10

Alnitak