Pantamtuy Pantamtuy - 6 months ago 30
MySQL Question

Get total amount per mode using Javascript

<?php
$ctr = 0;
while($ctr <= 10){
?>
<td><input required type='text' name='amount[<?echo $ctr; ?>]' class='amount'></td>
<td><input required type='text' name='mode[<?echo $ctr; ?>]' value='Cash'></td>
<?php
$ctr++;
}
?>
Total Amount: <span class="total_amount">0.00</span>
Total Cash : <span class="total_cash">0.00</span>
Total Check: <span class="total_check">0.00</span>

$(document).on('blur','.amount',function () {
var total = 0;
var total_cash = 0;
var total_check = 0;

$('.amount').each(function () {
total += parseFloat($(this).val());
});

$('.total_amount').html(total);
});


Using the code above, I can get the total amount of the number I encode in the input amount fields. How can I get the total per mode, cash(default) and check (user can change mode to check)?

Answer

If you sure, that next input width mode always corresponds, you can use JQuery.next. So it is necessary to check the value of each parameter to NaN.

$(document).on('blur','.amount',function () {
    var total = 0;
    var total_cash = 0;
    var total_check = 0;
    var val, mode;
    $('.amount').each(function () {
        val = parseFloat($(this).val());
        val = val ? val : 0;
        total += val;
        mode = $(this).next().val();
        switch(mode) {
            case "Check" : total_check += val; break;
            case "Cash"  : total_cash  += val; break;                
        } 
    });

    $('.total_amount').html(total);
    $('.total_cash').html(total_cash);
    $('.total_check').html(total_check);    
});

http://jsfiddle.net/ag0a78jd/

Comments