The value entered is displaying as not defined

As a newcomer to the world of javascript, I am diving into creating a simple To Do list. The basic functionality is there, but I'm scratching my head trying to figure out why the input value in my code keeps returning undefined.

The remove button is functioning perfectly fine, so at least one part of the code is working as expected.

    <!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 class="content__container">
          <div class="list__container">
            <div class="header__container">
              <h1 class="header__title">TO DO LIST</h1>
              <input id="header__input" type="text" />
              <button class="header__button">Add</button>
            </div>
            <div class="list__content"></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);

Answer №1

Your code currently only retrieves the input value when it initializes, not when the function is called.

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

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

    let toDoItem = document.createElement("li");
    let text = document.createTextNode(input);
    let 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 the listContent and the input variable inside the function will ensure that you always get the values each time the function is executed.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Save the contents of a file within an HTML table using jQuery

I needed to insert multiple files into the database by uploading and adding each file's content to a table. Once all files were added to the table, I included the table's values along with the file content in form data which was then passed to aj ...

Position three paragraphs in the center of a div container

Is there a way to center 3 paragraphs in a div? I have separate divs for each paragraph and one main div that holds all three nested divs. div.first { font-family: 'Kanit', sans-serif; color: aliceblue; width: 30%; float: left; ...

I'm getting a JS error saying that the variable "var" is not defined. Does anyone know how I can

Here is the code I am using to dynamically create a sitemap.xml file when accessing /sitemap.xml database = firebase.database(); var ref = database.ref('urls'); ref.on('value', gotData, errData); function errData(err){ ...

How does the Express server collaborate with Webpack middlewares to facilitate live reloading?

As I delve into node, express, and webpack, I find myself grappling with the concept of middleware. Upon examining the code snippet below, my current understanding is that once the web server is up and running and I navigate to http://localhost:7770/, the ...

Various filters have been utilized on an array of objects

Within one of my Vue components, the code structure is as follows: <li class="comment" v-for="comment in comments"> ... </li> Accompanied by a computed method: computed: { comments() { // Here lies the logic for filtering comment ...

AJAX request post parameters not recognized in ColdFusion form scope

I am currently developing a ColdFusion 8 training application that involves creating AJAX requests without using any libraries like jQuery. This is to support a basic CRUD application where data is retrieved and processed through various layers of the syst ...

Having trouble with clicking on an icon link within a list

Seeking assistance with creating a social media icon/link list for the first time on this platform. Any help is appreciated! <div class="social-links"> <ul> <li class="m-link"> <a href="&q ...

Updating the TextField in React Material UI based on the Slider value without affecting the Slider

Is there a way to update the value of a TextField based on the slider, while still allowing manual input in the TextField? I want the TextField to reflect changes from the slider but not vice versa. I attempted making the TextField a controlled component ...

CSS to resolve HTML alignment problems

I am new to HTML and CSS, trying to practice formulating a few things but my efforts are proving futile. Below is the code and images for your reference. I would appreciate your opinion. .container { display: block; width: 200px; height: 120px; } ...

Is there a way to ensure the collapsible item stays in its position?

I'm encountering an issue with the display of items within collapsible cards. Here is what it currently looks like: And this is how I want it to appear: Is there a way to achieve the desired layout using Bootstrap's Grid or Flex Layout? Here i ...

Preventing the removal of a choice by disabling it in the selector

I have a unique selector that is designed like this: <select id="patientSelector"> <option disabled selected style='display: none;' id="select0"> New Patients to Come</option> <option id="select1"></opt ...

Ways to display an icon in Angular 10 only when it is hovered over

Just getting started with Angular and still learning the concepts. Trying to figure out how to show an icon only when it's hovered over. Can anyone assist me? Sorry, can't share the code because of company rules. The icons are for sorting and ...

On one webpage, IE 11 is correctly styling certain visited hyperlinks while failing to do so for others

Although I acknowledge that others have asked similar questions, none seem to address the exact issue I am facing, nor do they offer practical solutions or clear explanations. Issue I'm encountering a problem where some visited hyperlinks in IE 11 f ...

Creating an object positioned to the right side of a div (div:right) is a matter of using CSS positioning properties

While we are familiar with pseudo-classes like :before and :after, have you ever wondered why there is no nav ul li a:left or :right? Do you think it's achievable? I'm open to using HTML5, CSS3, and JavaScript to make it happen. ...

Are you ready to create a Modal Factory?

For a while now, I have been utilizing modals in various front-end frameworks to communicate with users in my applications. Typically, the process involves defining the modal's html and then rendering it through a click event. As my apps continue to ...

What is the best way to assign table rows to various interfaces in typescript?

Assuming I have the interfaces provided below: export interface IUserRow { id: string, state: string, email: string, } export interface ITableRow { id: string, [key: string]: any; } export type Rows = ITableRow | IUserRow; // additio ...

Click on the link to see the jQuery effect in action

I'm trying to achieve a fade-out effect on the current page followed by fading in a new one. The fade-in effect is working fine, but when I click on the link, the new page loads without first fading out the existing content. The div that I want to app ...

Developing a transparent "cutout" within a colored container using CSS in React Native (Layout design for a QR code scanner)

I'm currently utilizing react-native-camera for QR scanning, which is functioning properly. However, I want to implement a white screen with opacity above the camera, with a blank square in the middle to indicate where the user should scan the QR code ...

An issue arises when attempting to remove or add attributes to the select box

In an attempt to change the 'disabled' and 'selected' properties, I am trying to set them to false and then apply the 'selected' and 'disabled' properties to the first option of a select box. Below is the code snippe ...

Complete Form Validation Issue Unresolved by Jquery Validation Plugin

I'm facing an issue with the jQuery validation plugin while attempting to validate a form. Strangely, it only works for one input field. Can anyone suggest a solution? <script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.valid ...