Reputation: 201
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.
Upvotes: 3
Views: 12718
Reputation: 5228
If you are calling the calculateAmount() function right after createDiv() depending on your page weight, it might happen that the DIV you create on the fly it's not written to the DOM yet and your each
function inside calculateAmount() it's not triggered. I recommend adding a JS delay
to give the browser the time to append the divs to the DOM. For the user, it will make no difference.
HTML
<table>
<tbody id="ProductDetail"></tbody>
</table>
JS
function createDiv(){
$("#ProductDetail").append("<tr><td ><div class='Amount'>"+Amount+"</div></td></tr>");
}
function calculateAmount(){
$('.Amount').each(function (i, obj) {
TotalAmountValue += parseInt($(this).text());
});
}
createDiv();
setTimeout(function () {
calculateAmount();
}, 400);
Upvotes: 0
Reputation: 125
Try using text()
$('.Amount').each(function (i, obj) {
TotalAmountValue += parseInt($(this).text());
});
Upvotes: 2
Reputation: 1587
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">
Upvotes: 5