0

I have a JSON Object from my SessionStorage. I want to display them on my view.

Object:

    0: {itemName: "Item 1", itemPrice: 0, itemQuantity: "1"}
    1: {itemName: "Item 2", itemPrice: 0, itemQuantity: "1"}
    2: {itemName: "Item 3", itemPrice: 0, itemQuantity: "1"}

What i tried so far is using JQuery to loop it but it displays Undefined.

JS:

var cartItems = JSON.parse(sessionStorage.cart);
$.each(cartItems, function(key, value) {

$("#cartList").html(
    '<li class="list-group-item d-flex justify-content-between align-items-center d-flex justify-content-between w-100">' +
        '<a>'+cartItems.itemName +'</a>' +
        '<a>'+cartItems.itemQuantity+'</a>' +
        '<span class="badge"><i class="material-icons large">keyboard_arrow_right</i></span>' +
    '</li>'
);

});

HTML:

<div class="list-group list-group-flush" id="cartList">
</div>

1 Answer 1

1

You are not accessing the values correctly inside the loop, it should be accessed as cartItems[key].itemName. The code may look like,

$.each(cartItems, function(index, value) {

    $("#cartList").html(
        $("#cartList").html() +
        '<li class="list-group-item d-flex justify-content-between align-items-center d-flex justify-content-between w-100">' +
        '<a>' + cartItems[index].itemName + '</a>' +
        '<a>' + cartItems[index].itemQuantity + '</a>' +
        '<span class="badge"><i class="material-icons large">keyboard_arrow_right</i></span>' +
        '</li>'
    );

});
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you! I got it. But it only displays the last data in the object(item 3).
@Ryan Please check the code I have put above. I have added $("#cartList").html() + inside the $("#cartList").html(), else the innerhtml will get replaced and will always show the last record.
Thank you! I used $("#cartList").append instead of .html to display it. But the accessing of the counts solved this for me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.