I have the following code: what I try to do is that when a new user wants to register in my project he must fill out the form 3 times once sent 3 times the record will be successful . For this reason I use localStorage
to save the data of the first, second and third sending of the form.
The code that I present in reality is an abstraction (minimum, complete and verifiable) of my real code (it would be a lot of code).
The code I publish does not work on SOes (I do not know why), please try it locally.
var nombreAux = "";
var apellidoAux = "";
var dato_G = []; //tiempo de presion y realce
var dato_aux = [];
var iteracion = 0;
$(window).on('load', function () {
$('#add-new-fact').click(function () {
var nombreUser = $('#nom').val();
var passUser = $('#pass').val();
var dato = $('#dato').val();
dato_aux.push(dato);
if (nombreUser != "" && passUser != "") {
/*Guardando los datos en el LocalStorage*/
nombreAux = localStorage.getItem("Nombre");
apellidoAux = localStorage.getItem("contrasena");
// alert(nombreAux+" "+apellidoAux);
if ((nombreAux == "" || apellidoAux == "")) {
localStorage.setItem("Nombre", nombreUser);
localStorage.setItem("contrasena", passUser);
}
nombreAux = localStorage.getItem("Nombre");
apellidoAux = localStorage.getItem("contrasena");
if (((nombreUser != nombreAux || passUser != apellidoAux))) { //cuando es nuevo user
localStorage.setItem("Nombre", nombreUser);
localStorage.setItem("contrasena", passUser);
dato_G.push(JSON.stringify(dato_aux));
localStorage['dato'] = dato_G;
dato = [];
}
if ((nombreUser == nombreAux || passUser == apellidoAux) && (iteracion < 6) && (typeof dato != undefined)) { //cuando ya es un usuario
iteracion++;
if (dato.length > 0) {
dato_G.push(JSON.stringify(localStorage['dato']));
dato_G.push(JSON.stringify(dato_aux));
dato_aux = [];
}
localStorage['dato'] = dato_G;
}
alert(localStorage['dato']);
location.reload();
if (iteracion == 3) {
//por medio de ajax recien envio los datos para su registro en la BD
}
return false;
}
alert(localStorage['dato']);
nombreUser = "";
passUser = "";
});
});
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="main.js"></script>
</head>
<body>
<input id="nom" type="text" placeholder="nombre">
<input id="pass" type="text" placeholder="pass">
<input id="dato" type="text" placeholder="dato">
<a href="#" id="add-new-fact" >enviar</a>
</body>
</html>
The result generates a array
"infected" or with garbage, similar to the screenshot below:
I would like to stay with only the arrays
. Is it possible?
Note: As you are inserting array
it will fill with more garbage.
How to avoid that garbage? Why is it generated?