Creating a task list using arrays and functions

I am working on developing a to-do list using an array in JavaScript, where the functions are separated from the HTML code. I have managed to set up the HTML structure, but I am facing challenges in completing the necessary functions. Fortunately, the EventListener is functioning properly in my project.


<form id="todoForm">
  <input id="todoInput" type="text">
  <button type="button" id="button">Add your To Do</button> 
</form>
<ol id="toDoList"></ol>

The key components of my project include an array named 'todos', detection of button clicks, and the 'addTodo' function that is triggered upon a click event to add input values to the array. However, I am currently struggling with the next function, 'printTodos', which should display the array items as li elements. This is where I require assistance as the existing content in the 'printTodos' function is not functional.

 var todos = [];

    document.getElementById('button').addEventListener('click', function 
    addTodo () {
    todos.push('input')  

    function printTodos () {
        var item = document.createElement("li");
        var node = createTextNode(input);
        // I am stuck 
    }
  });

Answer №1

Almost there, but it's not ideal to define the addTodo and printTodos functions inside the click event listener.

A better approach would be to declare the two functions outside of the event listener and then invoke them within it, like this:

var todos = [];

function addTodo() {
    var inputValue = document.getElementById('todoInput').value;
    todos.push(inputValue);
}

function printTodos() {
    var list = document.getElementById('toDoList');
    list.innerHTML = ''; //Clear the list before adding todos to avoid duplicates

    for (var i = 0; i < todos.length; i++) {
        var li = document.createElement('li');
        var listItem = li.appendChild(document.createTextNode(todos[i]));
        list.appendChild(listItem);
    }
}

document.getElementById('click', function() {
    addTodo();
    printTodos();
});

In the addTodo function, we fetch the input text from todoInput and add it to the array. Then, in the printTodos function, we iterate through the todos to create a new list item for each one. Finally, we append the new list items to the toDosList.

Answer №2

I have created a functional code pen demonstration for you to explore. Feel free to check it out or refer to the solution provided above. You can access the demonstration by clicking on this link https://codepen.io/waleedbinkhalid/pen/aRvwmo

 var todos = [];
    document.getElementById('button').addEventListener('click', function () {
 var list = $('#toDoList'); 
      var todoInput = $('#todoInput').val();
    todos.push(todoInput)  

        var item = document.createElement("li");
        for (var i = 0; i < todos.length; i++) {
        var listItem = $(document.createTextNode(todos[i]));
        list.append(document.createTextNode(todos[i]));
    }
  });
`

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

The process of updating UseContext global state in React Native and ensuring that the change is reflected across all screens

Struggling with updating global state values using React useContext on different screens? Attempting to change theme color in the App, but changes only appear on the current screen and not carried over to others? Looking for assistance in resolving this ...

Angular routes cause a glitch in the Bootstrap navbar, causing it to shift to the left on certain active

Apologies for the simple question, I am new to web design and couldn't find a solution even after extensive googling and searching. The issue I am facing is that when clicking on "EX5" or "EX6" in my navbar, it shifts to the left side of the screen i ...

Interactive marker popup appearing beyond the boundaries of the map container

Our popups are set to display outside of the map container initially, but when the map is moved, they adjust to fit inside the container with the correct anchor. However, upon inspecting the DOM, we noticed that the popups do not always have the correct an ...

NodeJS does not support the Array.Push method

I'm having trouble getting this code to work. I want to generate 5 random items from my database and store them in an array called 'dato'. However, when I print the array, it appears to be empty. /* GET users listing. */ router.get('/& ...

Change the CSS element if the current URL is not example.com/page1 or example.com/page2

When I apply the following JS code snippets, my output is incorrect or does not display at all. Below are the codes in question: if (location.href != "website.com/page1" || "website.com/page2") { element.style.backgroundColor='none'; ...

Reset the value of the input type file when the modal is closed and ensure that the Save All Changes button is deactivated

Hey there! Working on a simple project and trying to incorporate a neat trick in my app. I want to achieve the following: Clear the input type file value when the modal is closed. Essentially, if the user decides to cancel the upload and closes the modal, ...

Create an array of objects in JavaScript using JSON data

I have fetched a collection of dictionaries from my API: The data can be retrieved in JSON format like this: [{"2020-03-11 14:00:00":10.765736766809729} ,{"2020-03-11 15:00:00":10.788090128755387}, {"2020-03-11 16:00:00":10.70594897472582}, {"2020-03-11 1 ...

What is the reason behind TypeScript's decision not to raise an error in case of a mismatched function argument type?

Here's a simple illustration to showcase my point: type Info = { id: number; } type ImportantInfo = { id: number; value: 5; } type Task = (data: Info) => void; const task: Task = data => null; const data: ImportantInfo = { i ...

Divide the Array into Vertical Arrays

Here is my current result: [ '1', '1', '0', '0' ], [ '2', '4', '0', '0' ], [ '3', '7', '0', '0' ], [ '4', '0&apo ...

Utilizing JavaScript to Load and Showcase Images from a Temporary Image to imgsrc

How can I dynamically display images from the temporary image array 'tempimages' onto the 'img' element with the 'src' property? I have written a code that attempts to display temporary images from 'tempimages[]' on ...

Tips for adding a picture to a server and applying CSS filters to enhance it

I recently came across a set of CSS filters that can be applied to images by simply specifying the filter ID. Now, I'm looking to create a button that will allow me to save the edited image (with the filter applied) to a designated file location. I&a ...

Bringing JQuery into your Electron project through HTML

Working on some ElectronJS HTML coding and in need of using JQuery within the HTML. I've gone ahead and installed jQuery with npm install jquery. The question is, which file do I import to make use of JQuery? <!DOCTYPE html> <html lang="en" ...

managing, modifying and removing information within the app.controller in AngularJS

I am currently facing a challenge with my Javascript code for a simple web application that involves AngularJS. Here is the snippet of code I am working on: app.filter('startFrom', function () { return function (input, start) { if (i ...

Is there a way for me to extract the document title from firebase?

I have been trying to use this component to retrieve data, but I am encountering an issue where I cannot fetch the name of the document "sampleCloudFunction" under CloudFunctionMonitor (see image) from the database and display it. https://i.sstatic.net/kC ...

Verify if the date surpasses the current date and time of 17:30

Given a date and time parameters, I am interested in determining whether that date/time is greater than the current date at 17:30. I am hoping to achieve this using moment js. Do you think it's possible? This is what I have been attempting: let ref ...

What could be causing my problem with the add function?

I'm having trouble capturing the user input from modal input boxes and adding them to my state array. I've attempted to extract the values from the inputs and push them into a clone of the state array, then update the state with the clone. Howeve ...

Display a modal dialogue with an image on the initial page load for each user

Working on a project with Angular 11, Angular material, and Bootstrap, I encountered an issue. I want to display a popup ad the first time a user visits the home page. The modal dialog is created using Angular material, and I have it in the ads component, ...

How can I add a subdocument to a MongoDB array based on a specific condition being met?

When pushing sub documents into an array, the structure of the subdocs typically looks like this: { id:"someId", date:Date } The goal is to only add a new subdoc if there isn't already another subdoc with a matching id. The $addToSet modifier in ...

Connect-busboy causing NodeJS issue: TypeError - the method 'on' cannot be called on an undefined object

Recently I encountered an issue with a piece of my code: router.route("/post") .get(function(req, res) { // ... }) .post(authReq, function(req, res) { // ... // Get uploaded file var fstream; req.pipe(re ...

Leveraging Three.js Raycaster for a seamless PDF download functionality

Is there a way to trigger a PDF download when clicking on a 3D object in a Three.js scene? Below is an example of how I have set up the Raycaster: var raycaster; var mouse = { x: 0, y: 0 }; init(); function init() { raycaster = new THREE.Raycaster() ...