Home > Software design >  Input Value showing as undefined
Input Value showing as undefined

Time:10-06

I'm fairly new to javascript and trying to make a simple To Do list work. I have the basic functionality down, but I'm trying to understand why the input value in my code is returning undefined?

The remove button adds just fine, so I know the function is working.

    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <link rel="stylesheet" href="css/main.css" />
        <title>To Do List</title>
      </head>
      <body>
        <div >
          <div >
            <div >
              <h1 >TO DO LIST</h1>
              <input id="header__input" type="text" />
              <button >Add</button>
            </div>
            <div ></div>
          </div>
        </div>
        <script src="script.js"></script>
      </body>
    </html>
const btn = document.querySelector(".header__button");
const listContent = document.querySelector(".list__content");
let input = document.getElementById("header__input").value;

function addItem() {
  const toDoItem = document.createElement("li");
  const text = document.createTextNode(input);
  const remove = document.createElement("button");

  remove.textContent = "remove";
  remove.classList.add("list__remove");
  toDoItem.classList.add("list__items");

  toDoItem.appendChild(text);
  toDoItem.appendChild(remove);
  listContent.appendChild(toDoItem);
}

btn.addEventListener("click", addItem);

CodePudding user response:

Your script is getting the input value only when it start and not when the function is called.

const btn = document.querySelector(".header__button");

function addItem() {
    const listContent = document.querySelector(".list__content");
    let input = document.getElementById("header__input").value;

    const toDoItem = document.createElement("li");
    const text = document.createTextNode(input);
    const remove = document.createElement("button");

    remove.textContent = "remove";
    remove.classList.add("list__remove");
    toDoItem.classList.add("list__items");

    toDoItem.appendChild(text);
    toDoItem.appendChild(remove);
    listContent.appendChild(toDoItem);
}

btn.addEventListener("click", addItem);

Moving listContent and the input variable into the function will ensure that you get the values ​​every time the function is executed.

  • Related