Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery to loop through dynamically created elements with the same class

I have no. of div which is created dynamically in button click.

<table>
   <tbody id="ProductDetail"></tbody>
</table>

In button click, some no. of div are created with Amount value.

funtion createDiv(){
  $("#ProductDetail").append("<tr><td ><div class='Amount'>"+Amount+"</div></td></tr>");
}

I want to loop through these dynamically created div to get Amount values in jquery.I tried below code. But its not iterating loop.

function calculateAmount(){
    $('.Amount').each(function (i, obj) {
         TotalAmountValue=TotalAmountValue+$(this).html();
    });
}

Please anybody help me.

like image 261
sajbeer Avatar asked Apr 07 '26 05:04

sajbeer


2 Answers

I got this working just fine!

$(document).ready(function(){
          $("#ProductDetail").append("<tr><td><div class='Amount'>3</div></td></tr>");
          $("#ProductDetail").append("<tr><td><div class='Amount'>3</div></td></tr>");
          $("#ProductDetail").append("<tr><td><div class='Amount'>3</div></td></tr>");

          $("#sum").click(function()
          {
              var sum = 0;
              $(".Amount").each(function()
              {
                  sum += parseInt($(this).text());
              });
              alert(sum);
          });
      });

the .each iterates through all your elements that have the class Amount. Use the . selector for class and add the name. Index represents the position, while the val is the current element.

Edit: get a local variable and set it to 0. After that, iterate through all the elements with that class and take their text. Since it is String, js will try to convert the sum variable to String. You need to parse the text to int. This is a working example.

Here is the HTML

  <table>
      <tbody id="ProductDetail"></tbody>
  </table>
  <input type="button" id="sum" value="Sum">
like image 79
Simply Me Avatar answered Apr 09 '26 18:04

Simply Me


Try using text()

$('.Amount').each(function (i, obj) {
  TotalAmountValue += parseInt($(this).text());
});
like image 28
palawer Avatar answered Apr 09 '26 17:04

palawer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!