What is the process for including a task in the current method?

I've been working on building a web app similar to Google Calendar. I have successfully created the necessary objects and methods, but now I need to implement a feature that allows users to add tasks. My current idea is for users to input a task which will then be console.logged.

Does anyone have any suggestions?

HTML

<div class="new-task" id="task-input">
    <div id="add-new-task">Task: <input type="text"></div>
    <div id="add-time">Time: <input type="text"></div>
    <button class ="save-task" onclick="">Save task</button>
</div>

Javascript

var idCounter = 0
var tasksManager = {
    array: [],
    add: function(task){

        taskObject = {
            title: task,
            idVerification: idCounter ++
        }
        tasksManager.array.push(taskObject)
    },
    show:function(id){
        var i;
        for (i = 0; i < tasksManager.array.length; i++) {
           if(id === tasksManager.array[i].idVerification){
            return tasksManager.array[i]
           }
       }
    },
    delete:function(task){
       if(this.show){
       tasksManager.array.splice(task);
       }
    }

}

var newTask = document.getElementById("add-new-task")
newTask.addEventListener('click',tasksManager.add())

console.log(tasksManager.array)

As you can see from the console.log output above, the index [0] in the array is logged as undefined. My intention is for the user to input "Go to the gym" and have it added to the array instead.

Thank you!

Answer №1

Here are some issues that need attention:

  1. The click handler is not assigned properly and is executed immediately instead of on click.

  2. When using .add(), an argument specifying the task name should be provided.

  3. The click handler should be attached to the button element, not to the wrapping div containing the input element. Additionally, consider assigning an id attribute to the button.

  4. Value retrieval from the input element would be more appropriate if the input has an id instead of the surrounding div.

  5. The console.log function at the end of the script runs immediately; it should only execute when the user clicks the button.

Check out the modified snippet (corrections made in HTML as well):

var idCounter = 0
var tasksManager = {
    array: [],
    add: function(task){

        let taskObject = {
            title: task,
            idVerification: idCounter ++
        }
        tasksManager.array.push(taskObject)
    },
    show:function(id){
        var i;
        for (i = 0; i < tasksManager.array.length; i++) {
           if(id === tasksManager.array[i].idVerification){
            return tasksManager.array[i]
           }
        }
    },
    delete:function(task){
       if(this.show){
       tasksManager.array.splice(task)
       }
    }

}

var button = document.getElementById("save-task"); // <-- the button
var input = document.getElementById("add-new-task"); // <-- the input (move the ID attribute to the input!)
button.addEventListener('click', () => {
    tasksManager.add(input.value);
    console.log(tasksManager.array)
})
<div class="new-task" id="task-input">
    <div >Task: <input id="add-new-task" type="text"></div>
    <div id="add-time">Time: <input type="text"></div>
    <button class ="save-task" id ="save-task" onclick="">Save task</button>
</div>

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

Jumping over loop iteration following a JavaScript catch block

Currently, I am developing an API that requires making repeated calls to another API (specifically, Quickbooks Online) within a loop. These calls are encapsulated in promises that either resolve or reject based on the response from Quickbooks. Everything f ...

Dropdown box not displaying any choices

I developed a basic reusable component in the following way: Typescript (TS) import {Component, Input, OnInit} from '@angular/core'; import {FormControl} from '@angular/forms'; @Component({ selector: 'app-select', templa ...

Implementing defaultProps in conjunction with withStyles

Currently, I am in the process of developing a component using material-ui withStylers and defaultProps. However, I have encountered an issue where the props of the component are not being retrieved in the styles objects unless they are explicitly passed t ...

Assign tags using a variable within a loop

Consider the scenario where I need to generate a list of li elements: {map(listItems, (obj,i) => <li key={i}> <a target="_blank" href={obj.itemName === 'view_detail' ? `event/${id}` : ''} > <i c ...

Clicking on the LI element will automatically trigger a click event on the input radio button

Whenever I click on an li element, I want the corresponding radio input to be selected. However, when I try to do this, I'm seeing an error in the console log: Uncaught RangeError: Maximum call stack size exceeded How can I resolve this issue? Bel ...

Retrieving the data from an Angular website using a curl command

Currently, I am facing an issue with my Angular 2 application running on Google Earth. The problem arises as Google Earth uses an outdated version of Chrome that is not compatible with Angular 2. To tackle this obstacle, I need to find a way to initiate th ...

Guidelines for simultaneously modifying two dropdown select options

Is it possible to have one dropdown automatically change its value based on the selection made in another dropdown? For instance, if 'Value 1' is chosen from 'dropdown 1', can we set 'dropdown 2' to automatically display the ...

true not redirecting to 404 page when axios request fails

I have implemented Axios to access a basic API. My goal is to direct the user to the default Next.js 404 page in case of a failed request with a 404 error code. I have set the notFound boolean to true if the request status is 404. There are a total of 10 u ...

Does it typically occur to experience a brief pause following the execution of .innerHTML = xmlhttp.responseText;?

Is it common to experience a brief delay after setting the innerHTML with xmlhttp.responseText? Approximately 1 second delay occurs after xmlhttp.readyState reaches 4. This issue is observed when using Firefox 3.0.10. ...

Creating a customized component using unique styles in Material UI version 1

Currently, I am facing a challenge in styling my Card component with a width of 75 pixels while using Redux and Material UI V1. Despite following the example provided by Material UI on custom styling through withStyles and connect, I have not been able to ...

The function res.sendFile() does not display files on the browser

For the past few days, I've been facing a challenge. Does anyone have any suggestions? When I click on a login button, I authenticate the user, generate a token, store it in cookies, and then use it in the headers of a request to display the homepage. ...

If the cursor hovers over an image, the onmouseover function does not work properly

Currently, I am developing a PHP page to display data from a database in a tabular format. Each column in the table represents an 'ATC Station'. When active, additional data is displayed upon hovering over the cell. Everything was running smooth ...

"Step-by-step guide on showcasing a specific blog post using its unique identifier in an Angular/Express/MongoDB application

I'm struggling to figure out how to retrieve a single blog post by its ID, especially since I am new to this. Currently, my main blog application has an ng-repeat functionality that fetches all posts. What I really want is the ability to click on a p ...

Is there a way to efficiently process multipart/formdata, application/json, and text/plain within a single Express handler?

Operating an express demo server that mirrors the client's POST requests back to it is a part of an educational practice. In this exercise, the client makes a POST request using the fetch API, like so: fetch('http://localhost:5000/', { m ...

Are there any testing frameworks available for JavaScript that are similar to Junit and specifically designed for testing object-oriented JavaScript within Node

What are some recommended methods for testing object-oriented JavaScript in Node.js? For instance, let's consider the following Cat.js class: function Cat(age, name) { this.name = name || null; this.age = age || null; } Cat.prototype.getAge ...

Can someone explain the significance of receiving a TypeError when trying to access properties of null (specifically 'useRef') in a React application?

I encountered an issue while working on a React project...the browser console displays the following error. What does this mean? And how can I resolve it? react.development.js:1545 Uncaught TypeError: Cannot read properties of null (reading 'useRef ...

Oops! Looks like there was a glitch in the server for the application. The page you are looking for cannot be found. Error code: HTTP 404. Requested URL: /

Description: Oops! The page you are trying to access cannot be found. It may have been removed, renamed, or is currently unavailable. Please double-check the URL for any errors. Requested URL: /UsersPage/undefined I've got this AJAX script that is s ...

Maintain MUI Autocomplete in the open state even after making a selection from the

Whenever I select certain options on my Autocomplete component, I want to keep the component open. However, each time I click on onChange, the Autocomplete closes automatically and I can't seem to find a way to prevent this. Is there a workaround? In ...

Unable to successfully transfer a document

I am looking to upload a file onto my server. Here is what I have attempted: <input (change)="uploadImage($event.target)" hidden accept="image/*" #uploadProfileImage type="file"> uploadImage(event) { const profileImage = event.files.item(0); t ...

Ensure that a select input, dynamically generated, is marked as 'required' only when other inputs have been filled out

Displayed below is a snapshot of a page I'm developing that allows users to input details about various rooms in a property. Users have the ability to 'add' multiple rooms, triggering javascript/jQuery to dynamically create additional input ...