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));
};
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.
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));
};
Just before set item in localStorage check listArr wasn't empty:
if(listArr.length > 0){
localStorage.setItem("New Todo", JSON.stringify(listArr));
}