0

I have these input fields with same id, name. These inputs are generated using the ajax code as per the user choices. I want to do the sum of theses input fields(p_amount) in total_amount field using jquery.

<input type="text" id="p_amount" name="p_amount[]" placeholder="Enter Amount ">
<input type="text" id="p_amount" name="p_amount[]" placeholder="Enter Amount ">

<input type="text" id="p_amount" name="p_amount[]" placeholder="Enter Amount ">
<input type="text" id="p_amount" name="p_amount[]" placeholder="Enter Amount ">
<input type="text" id="p_amount" name="p_amount[]" placeholder="Enter Amount ">

<input type="text" id="total_amount" name="total_amount"  value="" placeholder="Total Amount">

I am using following js code but it only return the sum of digits entered in first text field. and i want sum of all the id's with p_amount. Please help me here.

<script type="text/javascript">
$('#total_amount').click(function() {
    var p_amount=$("#p_amount").val();
    var total = 0;
    for (var i = 0; i < p_amount.length; i++) {
        total += p_amount[i] << 0;
    }
</script>
4

2 回答 2

0

尝试这个,

var total=0;
$('#total_amount').click(function() {
    $("input[name='p_amount[]'").each(function(){
        total+=parseInt($(this).val());
    });
});
alert(total);
于 2013-05-28T10:53:00.430 回答
0

问题是id您使用的字段的 s 必须是不同的。您应该使用class属性来注释多个元素。

然后您可以使用 JQuery 获取这些并使用 .each() 遍历它们。

您可以在此处找到更多信息和示例: JQuery .each()

于 2013-05-28T10:50:22.557 回答