Click here to Skip to main content
15,310,056 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
If there is an item already, and the same item is added again then it should show "2 now" beside that grocery item. This number should increase every time the same item is added to the grocery list. this is the html part:
<!DOCTYPE html>
        <title>Grocery list</title>
        <meta charset="UTF-8">
        <link rel="stylesheet" href="">
        <link rel="stylesheet" href="grocery_style.css">
        <div class="container">
            <div class="groceries">
                <h1 style="text-align: center;">Grocery list</h1><br>
                <p style="text-align: center">Enter the items below:</p><br>
                <div style="text-align:center">
                    <input id="userinput" type="text" ><br><button class="btn btn-success" onclick="additem()" value="Add">Add Item</button>
                    "deleteall" class="fas fa-trash-alt">
                </div> <br>
                <div id="allitems"></div>
        <script src="grocery.js"></script>

What I have tried:

this is javascript part:

const groceries = document.getElementsByClassName("groceries")[0];
const deleteall=document.getElementById("deleteall");
const allitems=document.getElementById("allitems");
const userinput=document.getElementById("userinput");
    if(event.key == "Enter")
function additem(){
    var li= document.createElement("li");
    if (userinput.value == "") {
        alert("Enter some item");
        return false;
        if ( === "black") {
   = "red";
          } else {
   = "black";
Updated 19-Apr-21 5:30am

1 solution

You need a more code-oriented strategy instead of just displaying on the screen as list items.

Your shopping basket should be a javascript array of the item name (or other reference) and the count. This is a two-dimensional array.

When an item is added you can traverse the array and look for an item to match.

If you find the item then you increase the count element in the array.
If you do not find the item you add it to the end of the array.

Then you can loop through the array and regenerate your list. One reason why you would regenerate (instead of just modifying) is so you can also make an allowance for removing items as well. And even shorting them if you wish.


This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900