The onclick function in HTML will only be executed during the initial click event

I've been working on creating a To-Do list and have managed to add all the necessary functionalities. However, I encountered an issue where the edit function only works the first time it is clicked.

I tried searching for solutions online as I am relatively new to coding, but none of them seemed to solve the problem. The To-Do list allows for editing, saving, and deleting tasks, but the edit function fails to execute after the initial click.

const taskList = document.getElementById('task-list');
const taskInput = document.querySelector('input[type="text"]');

const addButton = document.getElementById('add-button');

window.onload = () =>{
  let savedTasks = localStorage.getItem('tasksList');
  taskList.innerHTML = savedTasks;
}

addButton.addEventListener('click' , ()=>{
    let title = taskInput.value;
    const taskElement = document.createElement('li');
    taskElement.classList.add('task');
      taskElement.innerHTML = `
        <input type="checkbox" onclick="window.checked()" class="checkBox">
        <span class = "title">${title}</span>
        <button class = "edit" onclick="edit()">Edit</button>
        <button class = "delete" onclick = "dlt()">Delete</button>
      `;
      taskList.appendChild(taskElement);
      taskInput.value = '';
      
      localStorage.setItem('tasksList', taskList.innerHTML);
});
    
const edit = ()=>{
  let parent = event.target.parentNode;

  let title = parent.querySelector('.title');
  title.contentEditable = true;
  title.focus();

  let editBtn = parent.querySelector('.edit');
  editBtn.innerText = 'Save';
  editBtn.addEventListener('click' , ()=>{
    title.contentEditable = false;
    editBtn.innerText = 'Edit';
    localStorage.setItem('tasksList', taskList.innerHTML);
  });

}

const dlt = ()=>{
  let parent = event.target.parentNode;
  parent.remove();
  localStorage.setItem('tasksList', taskList.innerHTML);
}

const checked = ()=>{
  let parent = event.target.parentNode;
  console.log(parent)
  let title = parent.querySelector('.title');
  if(parent.querySelector('.checkBox').checked){
    title.classList.add('checked');
  }
  if(!parent.querySelector('.checkBox').checked && title.classList.contains('checked')){
    title.classList.remove('checked');
  }

}


<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>To-Do List</title>
    <link rel="stylesheet" href="./style.css">
    <script src="app.js" defer></script>
  </head>
  <body>
    <h1>To-Do List</h1>
      <input type="text" placeholder="Add new task">
      <button id="add-button">Add</button>
    <ul id="task-list">

    </ul>
  </body>
</html>

Answer №1

The cause of this issue is

editBtn.addEventListener('click' , ()=>{ ... })

gets unset before it is set as "onclick=edit()"

A straightforward solution in my opinion is to assign only one event to one element, where you can differentiate it using an "if" condition wh

  if(title.contentEditable == 'false' || title.contentEditable == 'inherit' ){
    title.contentEditable = true;
    title.focus();
    editBtn.innerText = 'Save';
  } else {
    title.contentEditable = false;
    editBtn.innerText = 'Edit';
    localStorage.setItem('tasksList', taskList.innerHTML);
  }

as "inherit" is the default value for "contentEditable", and "false" indicates when editing is allowed

BTW - I have commented out localstorage because it causes errors on stack overflow snippets

const taskList = document.getElementById('task-list');
const taskInput = document.querySelector('input[type="text"]');

const addButton = document.getElementById('add-button');

window.onload = () =>{
  //let savedTasks = localStorage.getItem('tasksList');
  //taskList.innerHTML = savedTasks;
}

addButton.addEventListener('click' , ()=>{
    let title = taskInput.value;
    const taskElement = document.createElement('li');
    taskElement.classList.add('task');
      taskElement.innerHTML = `
        <input type="checkbox" onclick="window.checked()" class="checkBox">
        <span class = "title">${title}</span>
        <button class = "edit" onclick="edit()">Edit</button>
        <button class = "delete" onclick = "dlt()">Delete</button>
      `;
      taskList.appendChild(taskElement);
      taskInput.value = '';
      
      //localStorage.setItem('tasksList', taskList.innerHTML);
});
    
const edit = ()=>{
  let parent = event.target.parentNode;
  let title = parent.querySelector('.title');
  let editBtn = parent.querySelector('.edit');

  if(title.contentEditable == 'false' || title.contentEditable == 'inherit' ){
    title.contentEditable = true;
    title.focus();
    editBtn.innerText = 'Save';
  } else {
    title.contentEditable = false;
    editBtn.innerText = 'Edit';
    //localStorage.setItem('tasksList', taskList.innerHTML);
  }
}

const dlt = ()=>{
  let parent = event.target.parentNode;
  parent.remove();
  //localStorage.setItem('tasksList', taskList.innerHTML);
}

const checked = ()=>{
  let parent = event.target.parentNode;
  let title = parent.querySelector('.title');
  if(parent.querySelector('.checkBox').checked){
    title.classList.add('checked');
  }
  if(!parent.querySelector('.checkBox').checked && title.classList.contains('checked')){
    title.classList.remove('checked');
  }

}
<h1>To-Do List</h1>
      <input type="text" placeholder="Add new task">
      <button id="add-button">Add</button>
    <ul id="task-list">

    </ul>

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

Deactivate tooltips for the Ant Design tree component

Can the hover tooltips be disabled or customized? img I've experimented with various global CSS settings, but to no avail... I couldn't locate any information in the antd documentation regarding this. The antd selector seems to include this ele ...

I am looking to amalgamate a pair of scripts into a single cohesive work

Currently, I am utilizing jQuery toggleClass to switch CSS styles. $ (".test").click(function () { $(this).toggleClass('active'); }); Whenever I click outside of the Bootstrap menu, the menu gets hidden. In addition to this functio ...

What are the steps to resolve the issue of encountering the error message "Unrecognized custom element: <bot-ui>"?

I'm having some trouble setting up a chatbot screen with the "botui" and "vue-cli". Whenever I try to display the screen, I encounter an "Unknown custom element: " error. Below is the code snippet that I am using. Can you please help me figure out ...

Show the quantity of chosen selections utilizing ng-select

I have implemented the ng-select component for users to select multiple options from a list. My goal is to have the selected option displayed normally when only 1 option is chosen. However, if 2 or more options are selected, I want a custom template to sh ...

The Canvas feature does not support saving server side PHP code

I am facing an issue with saving a canvas to a directory and storing the URL in a database. Separately, saving the file or storing the URL in the database works fine. But when I combine both actions using AJAX to specify a PHP file, the session variable i ...

Ways to determine if a table row is expanded or not

Currently, I'm tackling an angular bootstrap table project that involves extendable rows. I'm trying to figure out a way to determine whether the row has been extended or not. Any suggestions on how this can be achieved? Here's the snippet ...

Please provide the text enclosed within the h1 tags

Is there a way to extract the content between <h2> </h2> tags in PHP or jQuery from each page and use it as the title of the pages to ensure uniqueness? Example: <section class="sub_header"> <h2>Contact</h2> < ...

The data is not being displayed in the table

I am encountering an issue while attempting to populate the table with data received through props by looping over it. Unfortunately, the data is not rendering on the UI :( However, when I manually input data, it does show up. Below is my code: Code for P ...

Modifying Django: What is the process for altering the HTML representation of a Django form component?

I've got a set of three select drop down boxes for selecting a date of birth. Here's how my Django template displays it: <label>Date of birth</label> {{ reg_form.date_of_birth }} However, I need to customize the HTML structure for e ...

jQuery performs perfectly in Chrome but encounters issues in IE9/IE8 and other older versions of Internet

I've implemented this lengthy jQuery script to enable dynamic dropdown loading and updating when selections are changed. However, I'm facing issues in Internet Explorer where the script loads the dropdowns initially but doesn't trigger oncha ...

Javascript Dilemma: Unable to Access 'object.style.left' and 'object.style.top' Values - What's the Issue?

Why am I unable to access and modify the object.style.left & object.style.top values? I am currently attempting to dynamically reposition a button on a webpage. In order to set new values for the style.left & style.top, I can utilize JavaScript l ...

Leveraging a spritesheet in conjunction with createPattern()

Looking for guidance on a task I can't find clear information on. I have a large sprite sheet named textures.png, with each texture being 64x64 pixels. My goal is to create patterns out of these textures. The createPattern() function works well but o ...

Tips for transferring a boolean value to a generic parameter in Java?

Looking to pass a boolean value to the Generic type in order to be utilized within a condition. This is the generic type interface OptionTypeBase { [key: string]: any; } type OptionsType<OptionType extends OptionTypeBase> = ReadonlyArray<Opt ...

Which types of responses does jQuery.ajax define as "successful"?

My jQuery AJAX post request seems to be triggering the error callback instead of success. I'm wondering if the unexpected 302 status code it is receiving could be the cause. After checking out the documentation, a question still lingers: How does jQu ...

What is the best way to detect the window scroll event within a VueJS component?

Looking to capture the window scroll event in my Vue component. This is what I have attempted so far: <my-component v-on:scroll="scrollFunction"> ... </my-component> I have defined the scrollFunction(event) in my component methods, but it ...

Changing the class when a checkbox is selected using JQuery

I’m working on a bootstrap switcher and I want to change the panel color from grey to green when the checkbox (switch) is checked. I had it working before, but after updating the switcher, it no longer functions properly. Here is the main code for the s ...

npm unable to retrieve Meteor package

When I attempted to install meteorite using nodejs v0.10.22 and npm v1.3.14, the installation failed with the following error: $ npm install meteorite npm http GET https://registry.npmjs.org/meteorite npm http 304 https://registry.npmjs.org/meteorite npm ...

What is the best way to prompt users to submit comments with a popup textarea box?

Within my project, I have incorporated a dropdown list: <div class="dropdown"> <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Select subject <span class="caret"></span> </but ...

Expanding and collapsing all divs with a single click using Jquery

I've gone through numerous resources but I'm still struggling to understand this concept. I have implemented a simple accordion based on this tutorial and now I want to include an "expand/collapse all" link. While I was able to expand all the ite ...

Implementing smooth transitions on iPad screens with responsive text

I am currently working on a personal project that involves creating images with hover transitions. The transition effect works perfectly on all browsers except for iPads. I'm facing an issue where I can't click on the image due to the presence of ...