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

132
Visualizações
How to exclude adding empty item to localStorage

I have a todo List on my website and I want to save all tasks that users write. But when users click on the "Add" button without entering a task, an empty line is stored in LocalStorage. What condition do I need to add to my code to exclude adding empty lines to LocalStorage. Right now my code for adding items looks like this:

 btn.onclick = function(){
        let userData = input.value;
        let getLocalStorage = localStorage.getItem("New Todo");
         if(getLocalStorage == null){
             listArr = [];
         } else{
             listArr = JSON.parse(getLocalStorage);
         }
         listArr.push(userData);
         localStorage.setItem("New Todo", JSON.stringify(listArr));
    };
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

What you can do is check whether your input is empty or not. Something like:

// This will check if the value is not null or undefined
// and the input length is greater than 0
if (input.value && input.value.length > 0) {
  // your logic here
}

You could trim the whitespaces as well, and check again wheter the length of the input is grater than 0 or not. This way, if someone just enters a bunch of spaces, it won't be added to your LS.

about 4 years ago · Juan Pablo Isaza Relatório

0

basically bail out at the beginning of the function if the value is empty or contains spaces only

 btn.onclick = function(){
         if (!input.value || !input.value.trim()) {
          return
        }
        let userData = input.value;
        let getLocalStorage = localStorage.getItem("New Todo");
         if(getLocalStorage == null){
             listArr = [];
         } else{
             listArr = JSON.parse(getLocalStorage);
         }
         listArr.push(userData);
         localStorage.setItem("New Todo", JSON.stringify(listArr));
    };

about 4 years ago · Juan Pablo Isaza Relatório

0

Just before set item in localStorage check listArr wasn't empty:

if(listArr.length > 0){
  localStorage.setItem("New Todo", JSON.stringify(listArr));
}
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