Is it possible to save a used browser object localstorage?

Asked

Viewed 204 times

5

I made a Todo list with 3 features: add an item, delete and clean the input field.

I would like the added items to be saved after reloading the page, it is possible to do this using the Localstorage? If not, how else can I save the added items?

Another doubt, how can I reset the input every time I add an item ?

Javascript:

function myFunction(){
    var test = document.getElementById("retorno").value;
    var listValue = document.createTextNode(test);

    var cre = document.createElement("LI");
    document.getElementById("todolist").appendChild(cre);
    cre.appendChild(listValue);
};

function clearFields(){
    document.getElementById("retorno").value = "";
}

function deleteField(){
    var del = document.getElementById("todolist");

    if (del.hasChildNodes()){
        del.removeChild(del.lastChild);
    }
}

HTML:

<input id="retorno" name="texto"type="text" placeholder="Add item here...">
<button id="botao" onclick="myFunction()" type="button">Add</button>
<button type ="button" onclick="clearFields();">Clear</button>
<button type="button" onclick = "deleteField();">Delete</button>
  • 1

    Both questions and answers are formatted with Markdown. Read Help with Markdown editing

  • Yes, it is. Links that can help you: https://answall.com/q/413997/99718 and https://answall.com/a/90597/99718

  • @Cypherpotato, even editing the question, has two different questions. I should flag it, but I think this question is very good to talk more about Javascript storage. Now, how do you do it ?

  • @Jeanextreme002 answers the main question if you have one and notifies you to create another question for each of the others. If all questions asked have the same focus and different contexts, vote to close with "Too wide".

3 answers

3

Answering your first question, yes it is possible to save values using localStorage after reloading the page. Actually, all the data saved on localStorage are stored on your computer, even if you close the browser or turn off the machine.

About "reset" the input after adding the item, you can do so by passing an empty string to the attribute .value at the end of its function. Thus:

function myFunction(){
    var test = document.getElementById("retorno").value;
    var listValue = document.createTextNode(test);

    var cre = document.createElement("LI");
    document.getElementById("todolist").appendChild(cre);
    cre.appendChild(listValue);
    test.value = "";
};
<input id="retorno" name="texto"type="text" placeholder="Add item here...">
<button id="botao" onclick="myFunction()" type="button">Add</button>
<button type ="button" onclick="clearFields();">Clear</button>
<button type="button" onclick = "deleteField();">Delete</button>

<ul id="todolist">

</ul>

  • @Valdeirpsr thanks for the tips, but his first question I answered or at least the alternative IF kk. I can’t tell you what other ways to save data than localStorage and sessionStorage because I don’t have a vast knowledge in Javascript or anything else related to web programming. If you can help in that part I appreciate.

3


Yes, it is possible to save the data in the browser with localStorage. Saved information is stored permanently in the browser until you delete it.

To delete what was typed in the input after clicking "Add", simply call the function clearFields() at the end of the function that adds (myFunction()).


A very functional way is to use another function to make the control of the localStorage. Know that the localStorage (LS) only stores strings, so the solution I suggest is to create an array of <li> from the list and save to LS. Then just recover the saved string, convert to array again with .split() and make a loop by creating the list HTML and inserting it into ul. The code below makes everything work (see the explanatory comments):

I did not create a snippet because it does not accept localStorage.

HTML

<input id="retorno" name="texto" type="text" placeholder="Add item here...">
<button id="botao" onclick="myFunction()" type="button">Add</button>
<button type ="button" onclick="clearFields();">Clear</button>
<button type="button" onclick = "deleteField();">Delete</button>
<ul id="todolist"></ul>

Javascript

// controla o localStorage
function ls(e){

   if(e){
      // aqui grava o localStorage
       var array = []; // cria a array
       var lista = document.querySelectorAll("#todolist li"); // pega todas as <li>
       for(var item of lista){ // percorre as <li>
          array.push(item.textContent); // insere os valores na array
       }

      localStorage.setItem("dados", array);
   }else{
      // aqui retorna
      return localStorage.getItem("dados");
   }
}

function myFunction(){
    var test = document.getElementById("retorno").value;
    var listValue = document.createTextNode(test);

    var cre = document.createElement("LI");
    document.getElementById("todolist").appendChild(cre);
    cre.appendChild(listValue);
    clearFields(); // limpa o input
    ls(true);

};

function clearFields(){
    document.getElementById("retorno").value = "";
    document.getElementById("retorno").focus(); // coloca o foco no input
}

function deleteField(){
    var del = document.getElementById("todolist");

    if (del.hasChildNodes()){
        del.removeChild(del.lastChild);
        ls(true);
    }else{
       localStorage.removeItem("dados"); // apaga o localStorage
    }
}

// aqui quando carrega a página
// verifica se há algo no localStorage "dados"
if(ls()){

   var lis = ''; // variável vazia
   var ls_array = ls().split(","); // converte o localStorage em array
   for(var item of ls_array){
      lis += '<li>'+item+'</li>'; // cria o HTML das <li>
   }

   document.getElementById("todolist").innerHTML = lis; // insere o HTML na ul
}
  • What use is the parameter "and" passed in function ls and if ? also did not understand the parameter "load" in myFunction

  • @Douglaskramer The parameter "and" serves to indicate whether the procedure will be written or read from Localstorage, its value, by default, is Undefined (false). The charges no use.

  • @Douglaskramer This. The charges forgot to erase.

1

As Jean has already said, yes, it is possible to save the data in the Torage locale, and they will remain there indefinitely. The data saved in localStorage remains there until it is cleared, i.e., it does not have an expiration date, other than sessionStorage, which clears the data as soon as the browser session is closed (the browser is closed).

To clear the input whenever you add an item, you just need to assign an empty string to it. I suggest you create a function that receives an input element and clean it, then, whenever you add the item to the list, you call the function by passing the object that references the input! : D

Thus:

function myFunction(){
    var test = document.getElementById("retorno").value;
    var listValue = document.createTextNode(test);

    var cre = document.createElement("LI");
    document.getElementById("todolist").appendChild(cre);
    cre.appendChild(listValue);
    test.value = "";
    
    //após ter feito a lógica toda (salvado o item na lista), chama a função de limpar o input:
    limpaInput(document.getElementById('retorno'));
};

function limpaInput(elemento){
  elemento.value = ''
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.