Save form values in LocalStorage / JSON - JavaScript

1

I'm trying to save the values of a form in the LocalStorage to then pass it to JSON, all in JavaScript, I appreciate a help with this, this is the code I have.

CODE:

var theForm = document.querySelector("#form"),
    valores = []; 

[].forEach.call(theForm.elements, 

    function(elemento){ 
    valores.push(elemento.value); 
});

localStorage.form = JSON.stringify({
    elementos: theForm.innerHTML,
    id: theForm.id || "form", 
    method: theForm.method || "GET", 
    action: theForm.action || "", 
    enctype: theForm.enctype || "", 
    datos: valores 
});
    
asked by ortizalfano 31.08.2018 в 20:47
source

1 answer

1

I leave this example that I made for your problem.

//obtener tu form desde el HTML
var form = document.getElementById('tuForm').elements;
for(var i = 0; i<= form.length - 1; i++){
    //aquí puedes agregar mas validaciones que ocupes
    //para efectos de prueba, yo solo permite que se obtuvieran los input de text.
    if(form[i].type == 'text'){
        //imprimir en consola el valor
        console.log(form[i].value);
        //la key sera el ID de tu elemento y despues se asigna el valor
        localStorage.setItem(form[i].id, JSON.stringify(form[i].value));
    }
}
//para probar que se guardaron bien los elementos, probamos en consola.
console.log(localStorage);

Remember that every time you save your form or actions the submit , you must clean the localStorage, if you do not do it, it could be overwriting data, or lost, etc.

I hope it works for you, regards.

    
answered by 12.09.2018 / 21:11
source