JQuery数组's和输入复选框+隐藏


JQuery array's and input checkbox + hidden

嘿,伙计们,我有一个有几个复选框的表,所有这些复选框都有一个隐藏的输入旁边的数值。我想在我的小表格底部的输入文本中显示这些的总和。我来到了脚本下面,但事实证明我的JS和JQuery知识是(方式?)最小。你知道最好的方法是什么吗?

<td>
    <input checked="checked" type="checkbox" class="processPaymentProducts" name="processPaymentProducts[]" value="<?=$transaction['student_transaction_id']?>" />
    <input type="hidden" id="prodPrice[<?=$transaction['student_transaction_id']?>]" name="prodPrice[<?=$transaction['student_transaction_id']?>]" value="<?=($transaction['student_transaction_amount_min']*100)?>" />
</td>
<script>
    $(document).ready(function() {
        $(".processPaymentProducts").click(function(){
            var amount;
            $amount = 0;
            jQuery.each($(".processPaymentProducts:checked").val(), function() {
                $amount += $(this).next('input').val();
                console.log($(this).next('input').val());
            });
            if($amount>100) { $amount = $amount/100; } else { $amount = 0; }
            $('#processPaymentAmount').val($amount);
        });
    });
</script>

对于初学者来说,您不需要在.next()中使用选择器。考虑到你的加价,next会工作得很好。此外,.each并不像你使用它时那样工作。我已经改了。此外,当基于输入值进行数学运算时,有时会得到未定义,这可能会使事情变得混乱。如果您在值选择器的末尾执行|| 0,如果您得到未定义的值,它将返回0。所以…这很好。试试吧。

$(document).ready(function() {
    $(".processPaymentProducts").click(function(){
        var amount;
        $amount = 0;
        $(".processPaymentProducts:checked").each(function() {
            $amount += $(this).next().val() || 0;
            console.log($(this).next().val() || 0);
        });
        if($amount>100) { $amount = $amount/100; } else { $amount = 0; }
        $('#processPaymentAmount').val($amount);
    });
});

html中的每个字段都是"string",字段中的偶数将被视为字符串。

所以你应该使用parseInt()方法将字符串转换成整数 例如,

这个代码:

$amount += $(this).next('input').val()
应该

$amount += parseInt($(this).next('input').val())

在完成所有计算后,记得将integer转换回string以将其放入field中。