Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

128
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda