【问题标题】:JQuery array's and input checkbox + hiddenJQuery数组和输入复选框+隐藏
【发布时间】:2011-08-19 09:11:13
【问题描述】:

大家好,我有一个带有几个复选框的表格,所有这些复选框在它们旁边的隐藏输入中都有一个数值。我想在我的小表格底部的输入文本中显示这些总和。我来到了下面的脚本,但事实证明我的 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>

【问题讨论】:

  • 我已经更新了演示和解释...希望对您有所帮助

标签: php javascript jquery jquery-selectors


【解决方案1】:

对于初学者,您不需要在 .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);
    });
});

【讨论】:

  • 谢谢!最大的问题是在每个循环中,这解决了这个问题
【解决方案2】:

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

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

例如,

这段代码:

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

应该是

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

完成所有计算后,记得将整数转换回字符串以将其也放入字段中。

【讨论】:

  • 有点同意...但是, parseInt 可能会被弄乱。如果你尝试 parseInt("8"),你会得到 8,但如果你尝试 parseInt("08"),你会得到 10(因为它使用八进制)。经验法则(根据 Javascript:The Good Parts)始终使用 parseInt 中的第二个参数。所以你应该使用 parseInt("08",10) 会给你十进制而不是八进制。祝你好运!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-10
  • 2011-05-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多