简体   繁体   English

计算使用AJAX生成的输入类型的总和

[英]Calculating sum of input type generated using AJAX

I have these input fields with same id, name. 我有这些具有相同ID,名称的输入字段。 These inputs are generated using the ajax code as per the user choices. 这些输入是根据用户选择使用ajax代码生成的。 I want to do the sum of theses input fields(p_amount) in total_amount field using jquery. 我想使用jquery在total_amount字段中完成这些输入字段的总和(p_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="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. 我正在使用以下js代码,但它仅返回在第一个文本字段中输入的数字总和。 and i want sum of all the id's with p_amount. 我想要所有ID与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>

The problem is that the id s of the fields you use must be distinct. 问题在于您使用的字段的id必须不同。 You should use class attributes for annotating multiple elements. 您应该使用class属性来注释多个元素。

Then you can get these with JQuery and iterate through them with .each(). 然后,您可以使用JQuery来获取它们,并使用.each()对其进行遍历。

You can find more information and examples here: JQuery .each() 您可以在此处找到更多信息和示例: JQuery .each()

Try this, 尝试这个,

var total=0;
$('#total_amount').click(function() {
    $("input[name='p_amount[]'").each(function(){
        total+=parseInt($(this).val());
    });
});
alert(total);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM