Home > OS >  Why does my code shows error when i Click the button
Why does my code shows error when i Click the button

Time:03-26

I am learning javascript. I am creating my notes app, but it's showing error to me. Please help to solve it.

let addBtn = document.getElementById('addBtn');

addBtn.addEventListener('click', function(e) {
  let addTxt = document.getElementById("addTxt").value;
  let notes = localStorage.getItem("notes");
  if (notes == null) {
    notesObj = [];
  } else {
    notesObj = JSON.parse(notes);
  }
  notes.push(addTxt);
  localStorage.setItem("notes", JSON.stringify(notes));
  addTxt.value = "";
  console.log(notes);
  console.log("clicked");
})

CodePudding user response:

You should be pushing onto notesObj, and stringifying that when saving back to localStorage.

Also, addTxt is a string, not the input element. To clear out the input element, you need to set the vaslue of the element, not the string.

let addBtn = document.getElementById('addBtn');

addBtn.addEventListener('click', function(e) {
  let addTxt = document.getElementById("addTxt").value;
  let notes = localStorage.getItem("notes");
  if (notes == null) {
    notesObj = [];
  } else {
    notesObj = JSON.parse(notes);
  }
  noteObjs.push(addTxt);
  localStorage.setItem("notes", JSON.stringify(notesObj));
  document.getElementById("addTxt").value = "";
  console.log(notes);
  console.log("clicked");
})

CodePudding user response:

As said in comments: push into the parsed Array, not into the LS retrieved String.

Here's a nicer remake:

// DOM utility functions:

const EL = (sel, par) => (par || document).querySelector(sel);

// Task:

const EL_add = EL("#addBtn");
const EL_txt = EL("#addTxt");

EL_add.addEventListener("click", (evt) => {
  // Prevent default browser action
  evt.preventDefault(); 

  // Trim your values from spaces!
  const addTxt = EL_txt.value.trim(); 

  // No text, do nothing
  if (!addTxt) return; 
  
  // Get nodes from LS or fallback to empty Array
  const notesArr = JSON.parse(localStorage.notes || "[]");

  // Add note
  notesArr.push(addTxt);

  // Save note
  localStorage.notes = JSON.stringify(notesArr);

  // Reset input value
  EL_txt.value = ""; 
})

CodePudding user response:

Firstly, notes is a string, which is fine. But is notesObj an array or an object? if it notes is null, it is an array, but otherwise it is an object. This inconsistency makes notes.push(addTxt) which is only available to array. When there is stuff in localStorage, there is no push function for object, so it will make an error. To fix, make a property on the notes object, such as 'data', which you can then do notesObj.data.push(txt), also, when the object is null, turn it into a {data:[]}

  • Related