Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

170
Visualizações
Why does my code shows error when i Click the button

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");
})
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

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");
})

about 4 years ago · Juan Pablo Isaza Relatório

0

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 = ""; 
})
about 4 years ago · Juan Pablo Isaza Relatório

0

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:[]}

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda