javascripthtmleventsevent-listenerappendchild

How to make a to-do list app present the input submitted to it


New coder here. I am trying to create a simple to-do list but clicking on the submit button is not returning any input.

Can you help me fix this? My code is below:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>To-Do List</title>
    <meta charset=""utf-8>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin="anonymous">
    <style>
        #interface {
            background-color: rgb(220, 216, 216);
        }

    </style>

</head>
<body class="container" id="interface">
    <h1>To-Do List</h1>
    <h2>By Thabo Mtetwa</h2>
    <h4 id= "description">From office tasks, to household chores, and personal memos - this to-do list is a great way to keep track of them all.</h4>     
    <div class="container">
        <h3>Item</h3>
        <input type="text" id="item-input" placeholder="Add item here">
        <br><br>
        <div button type="button" class="btn btn-primary" id="submit">Submit</button>
        </div>
        <div id="todo-container">
        </div>
    </div>
    <script>
        let inputField = document.getElementById("item-input");
        let addButton = document.getElementById("submit");
        let listArea =  document.getElementById("todo-container");

        addButton.addEventListener("click", function() {
            var listItems = document.createElement("li");
            ListItems.innerText = listArea.value;
            listArea.appendChild(ListItems);
        });
    </script>
</body>
</html>

I created a variable to capture the information submitted in the input field, and set it to present this information in the list area below the input field. But this has not worked.


Solution

  • Below there is an improved event handler

    addButton.addEventListener("click", function() {
      var listItems = document.createElement("li");
      listItems.innerText = inputField.value;
      listArea.appendChild(listItems);
    });
    

    See jsfiddle for an example of the working code.