-1

i got two copies of the same code with slight variation but seems the second one isnt working. I have tried using ChatGPT to identify issues however, nothing was found. But as far as i can see, it should work. But, everything i refresh, its removed. I want the buttons to stay there.

working code:

const todoList = document.querySelector(".todo-list");
const todoForm = document.querySelector(".add-todo");
const removeList = document.querySelector(".remove-List");

let items = JSON.parse(localStorage.getItem("todoList")) || [
  {
    title: "Write on, 'do not forget to', and press '+' to add",
    done: false,
  },
  {
    title: "press 'X' to remove",
    done: false,
  },
  {
    title: "search via 'search box'",
    done: false,
  },
  {
    title: "filter via 'all'",
    done: false,
  },
];

function addTodo(e) {
  e.preventDefault();
  const title = this.querySelector("[name=item]").value;
  const todo = {
    title,
    done: false,
  };
  items.push(todo);
  saveTodos();
  this.reset();
}

function createList(list = [], listTarget) {
  listTarget.innerHTML = list
    .map((item, i) => {
      return `<li>
      <input type="checkbox" id="todo${i}" data-index="${i}"
             ${item.done ? "checked" : ""} />
      <label for="todo${i}">${item.title}
                <span class="font-size:30px" data-index="${i}">X</span>
            </label>
    </li>`;
    })
    .join("");
}

function toggleDone(e) {
  if (!e.target.matches("input")) return;
  const el = e.target;
  const index = el.dataset.index;
  items[index].done = !items[index].done;
  saveTodos();
}

function removeSingle(e) {
  if (!e.target.matches("span")) return;
  const el = e.target;
  const index = el.dataset.index;
  items.splice(index, 1);
  saveTodos();
  if (items.length === 0) {
    removeList.classList.add("hidden");
  }
}

function saveTodos() {
  localStorage.setItem("todoList", JSON.stringify(items));
  createList(items, todoList);
  showRemoveButton();
}

function removeData() {
  items = [];
  localStorage.removeItem("todoList");
  createList(items, todoList);
  removeList.classList.add("hidden");
}

function showRemoveButton() {
  if (items.length > 1) return;
  removeList.classList.remove("hidden");
}

todoList.addEventListener("click", toggleDone);
todoList.addEventListener("click", removeSingle);
todoForm.addEventListener("submit", addTodo);
removeList.addEventListener("click", removeData);

// Init list
createList(items, todoList);
      <div class="ToDo-container">
        <header class="app-header">
          <div class="app-header1"> 
            <div class="title">
              <h1 class="app-title">ToDo List</h1>
            </div>
            <div class="select-button">
              <select id="filter">
                <option value="all">All</option>
                <option value="completed">Completed</option>
                <option value="incomplete">Incomplete</option>
              </select>
            </div>
          </div>
          <div class="search-header"> 
            <input type="text" id="search" placeholder="Search Todos">
            <button type="button" id="search-button" class="btn">Search</button>
          </div>
        </header>
        <section class="app-body">
          <div id="toDo">
            <ul class="todo-list"></ul>
            <form class="add-todo">
              <input
                type="text"
                placeholder="Don't Forget to..."
                name="item"
                required 
              />
              <input type="submit" value="+" />
            </form>
          </div>
          <button class="remove-List btn">Remove All</button>

        </section>
      </div>

// Add button function
function addButton() {
  // Prompt for button link and name
  var link = prompt("Enter the button link:");
  var name = prompt("Enter the button name:");

  // Create new button element
  var newButton = document.createElement("button");
  newButton.innerHTML = name;
  newButton.setAttribute("onclick", "location.href='" + link + "'");

  // Append new button to button container
  document.getElementById("button-container").appendChild(newButton);

  // Save buttons to local storage
  saveButtons();
}

// Remove buttons function
function removeButtons() {
  // Clear button container
  document.getElementById("button-container").innerHTML = "";

  // Save buttons to local storage
  saveButtons();
}

// Save buttons to local storage
function saveButtons() {
  // Get button container HTML
  var buttonHTML = document.getElementById("button-container").innerHTML;

  // Save button HTML to local storage
  localStorage.setItem("buttons", buttonHTML);
}

// Load buttons from local storage on page load
window.onload = function () {
  // Get button HTML from local storage
  var buttonHTML = localStorage.getItem("buttons");

  // Set button container HTML
  document.getElementById("button-container").innerHTML = buttonHTML;
};
      <div class="shortcuts-container">
        <header class="shortcut-header">
          <h1 class="shortcut-title">Quick Links</h1>
        </header>
          <section class="shortcut-body">
            <form id="button-form">
              <div id="button-container"></div>
              <button type="button" onclick="addButton()">Add Button</button>
              <button type="button" onclick="removeButtons()">Remove Buttons</button>
            </form>
          </section>
      </div>

i want some help with identifying the bug in my code

safalstha
  • 3
  • 4
  • This is a good opportunity for you to start familiarizing yourself with [using a debugger](https://stackoverflow.com/q/25385173/328193). When you step through the code in a debugger, which operation first produces an unexpected result? What were the values used in that operation? What was the result? What result was expected? Why? To learn more about this community and how we can help you, please start with the [tour] and read [ask] and its linked resources. – David Jan 27 '23 at 18:01
  • *I have tried using ChatGPT to identify issues however, nothing was found.* <-- Well, there's a first time you hear everything. – Scott Marcus Jan 27 '23 at 18:04
  • What is not working? We need details. – epascarello Jan 27 '23 at 18:17
  • thank you, i am looking into this thus taking me a while to reply. but, below, i will send a video link to show the issue at hand. its strange. – safalstha Jan 31 '23 at 16:15

1 Answers1

0

As you have mentioned that your "second one" is not working, I have focused on the second piece of code. This peice of code adds a button for which we need to provide a link and name via alert box, which is technically supposed to be a hyperlink. I have added 2 buttons using that and refreshed page multiple times but the newly added buttons always stay. Local storage is working just fine. Also, looking at your code, there is NO localStorage.removeItem() present. Hence the window.onload works fine. However, if you have any error logs in console of dev tools, please provide them for further debugging. Also, if there is a way for you attach a video link of testing with dev tools console visible that would really help to understand why it doesn't work for you.

Ameya Pai
  • 11
  • 1
  • 3