I am creating a shopping cart, and I want the total price to be updated when I click on the update button. Also, I want the new quantity and total price to remain the same after I refresh the page.

I'm using the wamp server.

Display code:

var products = JSON.parse(localStorage.getItem('products'));
var shoppingCart = JSON.parse(localStorage.getItem('shoppingCart'));
var itemQuantity;

function showItem(){
    var total=0;
    for(var i in shoppingCart) {
        var id = shoppingCart[i]; 
        var itemImage = products[id].image;
        var itemPrice = products[id].price;
        var itemDescription = products[id].description;
        itemQuantity=1;
        var totalPrice = parseInt(itemPrice*itemQuantity);

        var index = "<tr><td><img 
               src='img/"+itemImage+"'width='100px'/></td> 
               <td>"+itemDescription + "</td><td>" + itemPrice</td>
               <td><input id="+id+" type=number min=1 max=100 
               value="+itemQuantity+" /></td>
               <td>"+totalPrice+"</td>
               <td>"+ "<button 
               onclick='removeItem("+i+")'>Remove</button></td></tr>";

        $('#product_list').append(index);
        total += (totalPrice);
    } 
    document.getElementById('total').innerHTML = total;
    document.querySelector('.badge').innerHTML = shoppingCart.length;
}
showItem();

Update the total Price:

function saveCart() {
    localStorage.setItem('saveCart', JSON.stringify(shoppingCart));
};

function saveInput() { 
    localStorage.setItem('product', JSON.stringify(products));
};

$(document).ready(function(){
    $(".btn-update").click(function(){
        for(var i in shoppingCart) {
            var id= shoppingCart[i];
            itemQuantity = $("#"+id+"").val();
        }
        $("#product_list").empty();
        saveInput();
        showItem();
    });
});

HTML

        <table id="cart" border="0">
            <thead>
                <tr><th>Product</th><th>Description</th><th>UnitPrice</th> 
                <th>Quantity</th><th>Total Price</th></tr>

            </thead>
            <tbody id="product_list">

            </tbody>
            <tfoot id="cartFooter">
                <tr>
                    <th>TOTAL</th>
                    <th></th>
                    <th></th>
                    <th id="total" align="right">0</th>
                </tr>
            </tfoot>
        </table>

I expected the total price to be updated after I click the update button and the new quantity and new total price remain the same after I refresh.

0 Answers