javascriptjquerylocal-storageshopping-cartweb-storage

How to display only three items inside cart dropdown JavaScript?


I have shopping cart feature added in my ecommerce web app. So inside header there is a an icon of cart. So when anyone click on that icon dropdown appears which shows added items inside cart. So if I have added 10 items then dropdown becomes too lengthy too show. So I just want to display there only 2-3 items and see more button through which user can redirect to cart page and can see their added items.

Below is my script to display cart items in dropdown:

function displayCart(){
    var cart = JSON.parse(localStorage.getItem("cart"));
    var list = cart;
    var orderlist = "";
    if(list != null && list != 0){
        for(var i = 0 ; i < list.length ; i++) {
            var category = list[i].category;
            var productid = list[i].productid;
            var productname = list[i].productname;
            var pname = productname.replaceAll(' ','-');
            var quantity = list[i].quantity;
            var price_with_quantity = list[i].pprice;
            var image = list[i].productimage;
            orderlist = orderlist + "<li class=\"single-shopping-cart\">"
                    +"<div class=\"shopping-cart-img\">"
                       +"<input type=\"hidden\" id=\"hpid\" value="+productid+">"
                        +"<a href='singleproduct'>" 
                            +"<img alt="+pname+" src="+image+"/>"
                        +"</a>" 
                        +"<span class=\"product-quantity\">"+quantity+"x</span>"
                    +"</div>"
                    +"<div class=\"shopping-cart-title\">"
                        +"<h4>"
                            +"<a href='WebUrl.singleproduct'>"+productname+"</a>"
                        +"</h4>"
                        +"<span>&#8377;&nbsp;"+price_with_quantity+"</span>"
                        +"<div class=\"shopping-cart-delete\">"
                            +"<a href=\"#\" onclick=\"removeitem("+productid+");\"><i class=\"ion-android-cancel\"></i></a>"
                        +"</div>"
                    +"</div>"
                +"</li>";  
        }
    }else{
        orderlist = "<li>"
                        +"<div id=\"cart_empty\">No items in cart yet</div>"
                        +"<div id=\"ad_item\" style=\"text-align: center;\">Add items to your cart</div>"
                    +"</li>"
                    +"<div class=\"shopping-cart-btn text-center\">"
                        +"<a class=\"default-btn\" href=\"<%=WebUrl.login%>\">Login</a>"
                    +"</div> ";
        $(".shopping-cart-btn").hide();
    }
    document.getElementById('cartitems').innerHTML = orderlist;
}

How to display only 3 items in cart dropdown?

Screenshot to show cart


Solution

  • const listLength = list.length > 2 ? 2 : list.length
    for(var i = 0 ; i < listLength ; i++) {
        .....
    }