I am trying to make live input updating popover in my ecommerce site. It’s something like that I’ll give input on add cart option and popover will be able refresh and show current value. Everything is working fine except live update in popover. popover showing old value.
I am using bootstrap5.
function updateCart(cart) {
for (var item in cart) {
document.getElementById('div' + item).innerHTML = "<button id='minus" + item + "'class='btn btn-primary minus'>-</button> <span id='val" + item + "''>" + cart[item] + "</span> <button id='plus" + item + "' class='btn btn-primary plus'> + </button>";
}
localStorage.setItem('cart', JSON.stringify(cart));
document.getElementById('cart').innerHTML = Object.keys(cart).length;
console.log(cart);
updatePopover(cart);
}
// if plus or minus button is clicked, change the cart as well as the diplay value
// For plus
$('.divpr').on("click", "button.plus", function () {
b = this.id.slice(6,)
cart['pr' + b] = cart['pr' + b] + 1
document.getElementById('valpr' + b).innerHTML = cart['pr' + b]
updateCart(cart)
});
// For minus
$('.divpr').on("click", "button.minus", function () {
a = this.id.slice(7,)
cart['pr' + a] = cart['pr' + a] - 1
cart['pr' + a] = Math.max(0, cart['pr' + a]);
document.getElementById('valpr' + a).innerHTML = cart['pr' + a]
updateCart(cart)
});
function updatePopover(cart) {
console.log('we are inside udatePopover');
var popStr = "";
popStr = popStr + "<h5> Your selected Items </h5><div class=' mx-2 my-2'>";
var i = 1;
for (var item in cart) {
popStr = popStr + "<b>" + i + "</b>. ";
popStr = popStr + document.getElementById('name' + item).innerHTML.slice(0,15)+"..." + " Qty: " + cart[item] + '<br>'
i = i + 1;
};
popStr = popStr + "</div>"
console.log(popStr);
document.querySelector('[data-id="popcart"]').setAttribute('data-bs-content', popStr);
var popoverTriggerList = [].slice.call(document.querySelectorAll('[data-id="popcart"]'))
var popoverList = popoverTriggerList.map(function (popoverTriggerEl) {
return new bootstrap.Popover(popoverTriggerEl,
{
html: true
})
});
}
updatePopover(cart);