开发者

JQuery array's and input checkbox + hidden

Hey guys I have a table with a couple of checkboxes, all of those checkboxes have a numeric value in a hidden input next to them. I would like to display the sum of those in a input text at the bottom of my little table. I came as far as the script bellow but it turns out my JS and JQuery knowledge is (way?) to minimal. Any clue to what the best approach to this is?

<td>
    <input checked="checked" type="checkbox" class="processPaymentProducts" name="processPaymentProducts[]" value="<?=$transaction['student_transaction_id']?>" />
    <input type="hidden" id="prodPrice[<?=$transaction['student_transaction_id']?开发者_StackOverflow中文版>]" 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>


For starters, you don't need a selector inside the .next(). The .next will work fine given your markup. Further, the .each doesn't work like you are using it. I have changed it. Also, when doing math based on input values, sometimes you get undefined which can freak things out. If you do the || 0 at the end of your value selector, it will return 0 if you get an undefined. So... that is good. Try it out.

$(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);
    });
});


Every field in html is "string", even numbers in the fields would be treated like string.

So you should use parseInt() method to translate string into integer

for example,

this code:

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

should be

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

after you complete all the calculation, remember to translate integer back to string to put it into field, too.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜