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

138
Visualizações
Why is a string that is saved to local storage from a form input blank?

I'm trying to make a form that saves the data when the user presses a button.

   <form>
   <label for="name">Name:</label>
   <input type="text" id="name" name="name">
   <label for="age">Age:</label>
   <input type="text" id="age" name="age">
   <button type="button" onclick="SaveData()">Save Data</button>
   <button type="button" onclick="LoadData()">Load Data</button>
   </form>

Here is my attempt. When I try to load the data, it is just blank.

var name = document.getElementById("name").value;
function SaveData() {
    localStorage.setItem("name", name);     
}
function LoadData() {
    var data = localStorage.getItem("name");
    alert(data);
}
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You need to check #name value inside the function.

function SaveData() {
  var name = document.getElementById("name").value;
  localStorage.setItem("name", name);     
}
about 4 years ago · Juan Pablo Isaza Relatório

0

Note that name is set outside saveData() and never updated. Thus, whenever saveData() is called, it's always storing the original value of name, which (since the form input has no default) is the empty string. Thus it's more accurate to say that it's loading the default value, rather than a blank value.

To store the current value of the input, you'll need to update name before each time saveData() is called or access the value directly in saveData(). Since there are multiple inputs, you'd need to do this for each input. A simple solution is to pass the form to saveData() and have it examine each of the inputs in the form:

function saveData(form) {
    for (elt of form.elements) {
        if (elt.id || elt.name) {
            localStorage.setItem(elt.id || elt.name, elt.value);
        }
    }
}

The "Save" form button would be updated as:

<button type="button" onclick="SaveData(this.form)">Save Data</button>

You can make similar changes to LoadData() and the "Load" button.

Instead of calling the data saving & loading functions from the onclick properties, you could also make use of addEventListener (which has certain advantages, as outlined both in the linked MDN document and "addEventListener vs onclick" here on SO), though passing the form would be handled differently.

about 4 years ago · Juan Pablo Isaza Relatório

0

  <form onsubmit="onSave()">
   <label for="name">Name:</label>
   <input type="text" id="name" name="name">
   <label for="age">Age:</label>
   <input type="text" id="age" name="age">
   <input type="submit" value="Save Data" />
   <button type="button" onclick="LoadData()">Load Data</button>
   </form>
function onSave(event){
    event.preventDefault();
    const { currentTarget } = event;
    const data = new FormData(currentTarget)
    Array.from(data.entries()).forEach(function([key, value]) {
      window.localStorage.setItem(key, value);
    })
}

OR

  <form id="form">
   <label for="name">Name:</label>
   <input type="text" id="name" name="name">
   <label for="age">Age:</label>
   <input type="text" id="age" name="age">
   <button type="button" onclick="SaveData()">Save Data</button>
   <button type="button" onclick="LoadData()">Load Data</button>
   </form>
const form = document.getElementById("form")
function onSave(event){
    const data = new FormData(form)
    Array.from(data.entries()).forEach(function([key, value]) {
      window.localStorage.setItem(key, value);
    })
}

Check this for more information

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