Event listener not working

Hi, I am making a todo list web app which takes an input and displays it in an another section. Once a task is done, you can remove those by clicking on the task. I am getting problem in removing the task. The console shows error in addEventListener. The code is down below

HTML

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="preconnect" href="https://fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@500&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="sass/style.css">
    <script src="js/index1.js" type="module"></script>
    <title>To Do List</title>
</head>

<body>
    <main>
        <section class="newItemEntry">
            <form id="itemEntryForm">
                <label for="newItem">Enter a new to do item</label>
                <input id="newItem" type="text" autocomplete="off" placeholder="Add item" tabindex="0">
                <button id="addItem" class="button" title="Add new item" aria-label="Add new item to list" tabindex="0">+</button>
            </form>
        </section>
        <section class="listContainer">
            <div class="listTitle">
                <h1 tabindex="0">To Do List</h1>
                <button id="clearItem" class="button" title="Clear The List" aria-label="Remove all items from the list" tabindex="0">Clear</button>
            </div>
            <hr>
            <div id="listItems">
                <!-- <div class="item">
                    <input type="checkbox" id="1" tabindex="0"><label for="1">eat</label>
                </div>
                <div class="item">
                    <input type="checkbox" id="2" tabindex="0"><label for="2">code</label>
                </div> -->
            </div>
            <p class="confirmation" id="confirmation" aria-live="assertive"></p>
        </section>
    </main>
</body>

</html>

JAVASCRIPT

<script>
    //to create the list

    var mainList = [];

    if (localStorage.getItem("data") != null) {
        const getList = localStorage.getItem("data");
        mainList = JSON.parse(getList);
    }

    document.addEventListener("readystatechange", (event) => {
        if (event.target.readyState === "complete") {
            console.log("loaded");
            initialise();
        }
    });

    function initialise() {
        document.getElementById('addItem').addEventListener("click", (event) => {
            event.preventDefault();
            const test = getEntry();
            if (test != '') {
                mainList.push(test);
                updateData();
                clearList();
                loadList();
                document.getElementById("newItem").value = '';
            };
        });

        document.getElementById("clearItem").addEventListener("click", (event) => {
            if (confirm("Are you sure to clear the list?")) {
                clearList();

                //  to clear the local storege
                localStorage.removeItem("data");
            };
        });

        removeListItem();

        clearList();
        loadList();
        console.log("init working");
    }

    function loadList() {
        console.log("load working");
        for (let i = 0; i < mainList.length; i++) {
            console.log("loop working", i, mainList.length, mainList);
            const div = document.createElement("div");
            div.className = "item";
            const inp = document.createElement("input");
            inp.type = "checkbox";
            inp.tabIndex = "0";
            inp.id = ++i;
            removeListItem(inp, inp.id);
            const lab = document.createElement("label");
            lab.htmlFor = inp.id;
            i--;
            lab.innerHTML = mainList[i];
            document.getElementById("listItems").appendChild(div);
            div.appendChild(inp);
            div.appendChild(lab);
        };
    }

    function getEntry() {
        return document.getElementById('newItem').value.trim();
    }

    function clearList() {
        document.getElementById("listItems").innerHTML = '';
    }

    function updateData() {
        localStorage.setItem("data", JSON.stringify(mainList));
    }

    function removeListItem(inp, id) {
        inp.addEventListener("click", () => {
            inp.remove();
            mainList.splice(id, 1);
            updateData();
        })
    }
</script>

hey @acoderg,

I think this is what you want? clicking the item label will remove it from the list, i changed some of your other code too for better readability so you can just use the bits you need if you want, if theres something you dont understand in it let me know :slight_smile:

const listItems = document.getElementById("listItems");
const addButton = document.getElementById("addItem");
const clearButton = document.getElementById("clearItem");
const input = document.getElementById("newItem");
const getList = localStorage.getItem("data");
const storedData = JSON.parse(getList);
let mainList = storedData ? storedData : [];


document.addEventListener("readystatechange", (event) => {
  if (event.target.readyState === "complete") {
    console.log("loaded");
    initialise();
  }
});

function initialise() {
  addButton.addEventListener("click", addItem);
  clearButton.addEventListener("click", clearItems);
  loadList();
  console.log("init working");
}

function removeItem(itemName, itemId) {
  if (confirm(`Remove ${itemName} from the list?`)) {
    const filteredList = mainList.filter((name) => name !== itemName);
    mainList = filteredList;
    updateData();
    const clickedItem = document.getElementById(itemId);
    clickedItem.remove();
  }
}

function addItem(e) {
  e.preventDefault();
  const inputValue = getEntry();

  if (inputValue) {
    mainList.push(inputValue);
    const newListItem = createItem(inputValue);
    listItems.appendChild(newListItem);
    updateData();
    input.value = "";
  }
}

function loadList() {
  mainList.forEach((itemName) => {
    const newListItem = createItem(itemName);
    listItems.appendChild(newListItem);
  });
}

function getEntry() {
  return input.value.trim();
}

function clearItems() {
  if (confirm("Are you sure to clear the list?")) {
    listItems.innerHTML = "";
    mainList = [];
    localStorage.removeItem("data");
  }
}

function updateData() {
  localStorage.setItem("data", JSON.stringify(mainList));
}

function createItem(itemName) {
  const itemId = `id_${itemName}${mainList.length}`;
  const div = document.createElement("div");
  div.className = "item";
  div.id = itemId;
  const input = document.createElement("input");
  input.type = "checkbox";
  const label = document.createElement("label");
  label.htmlFor = itemId;
  label.innerHTML = itemName;
  label.onclick = () => removeItem(itemName, itemId);
  div.appendChild(input);
  div.appendChild(label);
  return div;
}


This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.