JSFiddle - React, Tailwind, and code Playground

by avidal

HTML

<table class="stripeMe" cellpadding="0" cellspacing="0" width="100%">
    <tbody>
        <tr>
            <th>
                MEALS
            </th>
            <th style="text-align: center;">
                01/9
            </th>
            <th style="text-align: center;">
                01/10
            </th>
            <th style="text-align: center;">
                01/11
            </th>
            <th style="text-align: center;">
                01/12
            </th>
            <th style="text-align: center;">
                01/13
            </th>
            <th style="text-align: center;">
                01/14
            </th>
            <th style="text-align: center;">
                01/15
            </th>
            <th style="text-align: center;">
                Total
            </th>
        </tr>
        <tr id="118">
            <td>
                HEALTHY BALANCE
            </td>
            <td style="text-align: center;">
                <input type="text" style="text-align: center;" size="3" class="sum" id="118|1/9/2011"
                name="118|1/9/2011" value="0" />
            </td>
            <td style="text-align: center;">
                <input type="text" style="text-align: center;" size="3" class="sum" id="118|1/10/2011"
                name="118|1/10/2011" value="9" />
            </td>
            <td style="text-align: center;">
                <input type="text" style="text-align: center;" size="3" class="sum" id="118|1/11/2011"
                name="118|1/11/2011" value="0" />
            </td>
            <td style="text-align: center;">
                <input type="text" style="text-align: center;" size="3" class="sum" id="118|1/12/2011"
                name="118|1/12/2011" value="9" />
            </td>
            <td style="text-align: center;">
                <input type="text" style="text-align: center;" size="3" class="sum" id="118|1/13/2011"
                name="118|1/13/2011" value="9" />
   ...

JavaScript

$('input.sum').change(function() {
    var sum = 0;
    
    // we want to sum up the values of all input.sum elements that are in the same tr
    // as this one
    $(this).closest('tr').find('input.sum').each(function(i) {
        var val = parseInt($(this).val(), 10);
        /*
        change the above line to:
        var val = parseFloat($(this).val());
        if the inputs will be floats
        */
        if (isNaN(val) || val === undefined) {
            return;
        }

        sum += val;
    });

    $(this).closest('tr').find('input.total').val(sum);

});