Reputation: 1673
Can anybody advise why my Jquery loop (using each) displays all the past additions aswell? For instance, if I am adding item no 4 and items 1,2,3 are added it will display 1,2,3,1,2,3,4.... Any ideas?
function refreshCart(){
console.log("in current cart")
var cartTable = $(".cart-table")
var cartBody = cartTable.find(".cart-body")
var productRows = cartBody.find(".cart-product")
var currentUrl = window.location.href
var refreshCartUrl = '/api/cart/'
var refreshCartMethod = "GET";
var data = {};
$.ajax ({
url: refreshCartUrl,
method: refreshCartMethod,
data: data,
success: function(data) {
console.log("success")
console.log(data)
if (data.products.length > 1) {
productRows.html("")
$.each(data.products, function(index, value) {
cartBody.append("<tr><th scope=\"row\">" + index + "</th><td colspan=3>" + value + "</td></tr>")
})
} else {
window.location.href = currentUrl
}
},
error: function(errorData) {
console.log("error")
console.log(errorData)
}
})
}
Upvotes: 1
Views: 64
Reputation: 50
The problem is that your dom element is not emptied when you refresh the cart a second time. So there's nothing wrong with the loop itself, you just have to empty the dom element before. Like this:
$(cartBody).empty()
Just do this after you've fetched the cartBody and you should be all set! :)
Upvotes: 2
Reputation: 3795
I think you need few change see following:
success: function(data) {
console.log("success")
console.log(data)
if (data.products.length > 1) {
var allProduct = '';
$.each(data.products, function(index, value) {
allProduct += "<tr><th scope=\"row\">" + index + "</th><td colspan=3>" + value + "</td></tr>";
})
$(cartBody).html(allProduct); // Replacing your existing html here
} else {
window.location.href = currentUrl
}
}
Upvotes: 0
Reputation: 443
you remove content of cart-product with the line productRows.html("") but you append the content to cart-body without delete his content before. That's why it append the same datas twice. Delete cart-body content before the loop.
Upvotes: 0