table row calculation

by Oliver Kelso

HTML

<table id="myTable">
    <thead>
        <th>No</th>
        <th>Goods<span class="red">*</span>
        </th>
        <th>Quantity<span class="red">*</span>
        </th>
        <th>Value per unit<span class="red">*</span>
        </th>
        <th>Total<span class="red">*</span>
        </th>
    </thead>
    <tr>
        <td class="labelcell">1</td>
        <td class="datacell">
            <input type="text" class="goodsDesc" name="goodsDesc[<?php echo $i; ?>]" maxlength="200" />
        </td>
        <td class="datacell">
            <input type="text" class="k8goodsQty" name="k8goodsQty[<?php echo $i; ?>]" maxlength="200" />
        </td>
        <td class="datacell">
            <input type="text" class="valuePerUnit" name="valuePerUnit[<?php echo $i; ?>]" maxlength="200" />
        </td>
        <td class="datacell">
            <input type="text" class="valueTotal" name="valueTotal[<?php echo $i; ?>]" maxlength="200" />
        </td>
    </tr>
    <tr>
        <td class="labelcell">2</td>
        <td class="datacell">
            <input type="text" class="goodsDesc" name="goodsDesc[<?php echo $i; ?>]" maxlength="200" />
        </td>
        <td class="datacell">
            <input type="text" class="k8goodsQty" name="k8goodsQty[<?php echo $i; ?>]" maxlength="200" />
        </td>
        <td class="datacell">
            <input type="text" class="valuePerUnit" name="valuePerUnit[<?php echo $i; ?>]" maxlength="200" />
        </td>
        <td class="datacell">
            <input type="text" class="valueTotal" name="valueTotal[<?php echo $i; ?>]" maxlength="200" />
        </td>
    </tr>
</table>

JavaScript

function calculate(){
    
    var quantity = '.k8goodsQty';
    var cost = '.valuePerUnit';
    var total = '.valueTotal';
    var rowTotals = new Object();
    var i = 0;
    
    $(':not(thead) > tr').each(function(){
        
        var row = 'dataRow-' + i;
        
        $(this).addClass(row);
 
        $('.' + row + ' ' + quantity + ', ' + '.' + row + ' ' + cost).on('keyup', function(){
            
            var quantityVal = $(quantity).val();
            var costVal = $(cost).val();
            var calc = parseFloat(quantityVal * costVal);
            rowTotals.i = calc;
            //rowTotal.push(parseFloat(quantityVal * costVal));
            
            //console.log('.' + row + ' ' + total);
            console.log(rowTotals.i);
            
            $('.' + row + ' ' + total).val(rowTotals.i);
            
        });
        
        i++;
        
    });

    rowTotal = 0;
}

$('#myTable').on('load', calculate());