使用Javascript获取每种模式的总金额

时间:2015-07-06 00:17:18

标签: javascript php html

 <?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);
});

使用上面的代码,我可以在输入金额字段中获得我编码的总数。如何获得每种模式的总计,现金(默认)和检查(用户可以更改模式以进行检查)?

3 个答案:

答案 0 :(得分:1)

以下仅适用于索引一致的情况(例如,每个amount[x]都有mode[x]):

var total = {};

$('.amount').each(function(idx)
    {
        var mode = $('[name="mode['+idx+']"');

        if (!total[mode.val()])
            total[mode.val()] = 0;

        total[mode.val()] += parseFloat($(this).val());
    }
);
console.log(total);

jsFiddle

答案 1 :(得分:1)

如果您确定下一个输入宽度mode始终对应,则可以使用JQuery.next。因此有必要检查每个参数的值为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/

答案 2 :(得分:0)

使用jquery获取&#34; amount&#34;的集合中当前元素的索引。元件。

var index = $( ".amount" ).index( this );

使用上面的索引获取相应的Cash / Check元素值

var mode_value = $("input[name='mode["+index+"]']").val();

然后检查该值并将值存储在正确的变量

if (mode_value == "Cash")
total_cash = total_cash + $(this).val();

if (mode_value == "Check")
total_check = total_check + $(this).val();

整个代码必须在模糊事件中。

相关问题