Save data with JSON medainte input text in localStorage

0

I have a job to deliver in a few hours but it does not work out. I do not know if someone can help me. What I have to do is that when I add a new element and save the text it is uploaded to the localStorage and that when that element array is deleted, the problem is that I do not know how to handle the array with the input text .

I leave the code for you to verify it.

<html>
<head>
<script>
if (typeof(Storage) !== "undefined")
{
//si hay soporte se agrega la llamada
//localStorage.setItem("nombre","ludwig"); //nombre es igual a ludwig
//localStorage.setItem("clave","230512");

function mostrar()
{
document.getElementById("nombre").innerHTML=localStorage.getItem("nombre");
}
function editar()
{
var nombre = prompt("proporcione el nombre");
localStorage.setItem("nombre",nombre);
}
function eliminar()
{
localStorage.removeItem("nombre");
}
function agregarPersona(id)
{
fila=document.createElement("tr");
col1=document.createElement("td");
col2=document.createElement("td");

inText = document.createElement("INPUT");
inText.setAttribute("name","Nombre[]");
inText.setAttribute("class","input-text");
inText.setAttribute("type","text");
inText.setAttribute("readonly","readonly");

if(id)
{
console.log("no es vacio");
inText.setAttribute("value",id);
}
else
{
console.log("es vacio");
}

col1.append(inText);

btn1=document.createElement("a");
btn2=document.createElement("a");

btn1.setAttribute("href","#");
btn1.setAttribute("class","btn btn-primary");
btn1.setAttribute("onclick","delProducto(this);");
btn1.innerHTML="eliminar |";

btn2.setAttribute("href","#");
btn2.setAttribute("class","btn btn-primary");
btn2.setAttribute("onclick","editProducto(this);");
btn2.innerHTML="editar";

col2.append(btn1);
col2.append(btn2);



fila.appendChild(col1);
fila.appendChild(col2);

document.getElementById("tb").appendChild(fila);
}
function editProducto(obj) //Es el boton de editar
{
var trActual = obj.parentNode.parentNode; // seleccionamos el tr donde se encuentra el boton.
if (obj.innerHTML.toLowerCase()=="editar")
{
trActual.getElementsByClassName("input-text")[0].removeAttribute("readonly");
obj.innerHTML = "guardar";
}
else
{
trActual.getElementsByClassName("input-text")[0].setAttribute("readonly","readonly");
obj.innerHTML = "editar";
trActual.removeAttribute("class");
localStorage.setItem("name", "Nombre[]");
}
}
function delProducto(obj)
{
if (confirm("¿Desea eliminar?")==true)
{
obj.parentNode.parentNode.remove();
localStorage.removeItem("name", "Nombre[]");
return true;
}
else
{
return false;
}
}
function cargarDatos()
{
JsonText = localStorage.getItem("myLocalStorage");
myLocalStorage = JSON.parse(JsonText);

for (var i in myLocalStorage.personas.persona)
{
agregarPersona(myLocalStorage.personas.persona[i].nombre);
}
}
//datos de ejemplo
myLocalStorage = {"personas":{"persona":[{"nombre": "Daniel Lopez Cortazar"}]}};
myLocalStorage = JSON.stringify(myLocalStorage);
localStorage.setItem("myLocalStorage", myLocalStorage);
}
else
{
//debemos decir que no tiene soporte
document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Storage...";
}
</script>
</head>

<body>
<div class="container-fluid">
<h1 id="nombre"></h1>
<a href="#" onclick="mostrar()">Muestra datos</a>
<a href="#" onclick="editar()">Edita datos</a>
<a href="#" onclick="eliminar()">Eliminar datos</a>

<h2>Lista de personas</h2>
<a class="btn btn-primary" onclick="agregarPersona();">Agregar</a>

<table class="table" id="tb">
<tr>
<th>Nombre</th>
<th>Operacion</th>
</tr>
</table>
<a href="javascript:;" onclick="cargarDatos();">Cargar datos</a>
</div>
</body>
</html>

    
asked by Oscar Santillán 25.04.2018 в 17:47
source

1 answer

0

I do not know if I understood you well, but if what you need is to eliminate an element of an array, what you should do is get the index of the element in the array and then use the splice function to "remove" it from the array to finally return to save the arrangement, it would be something like that.

var nombres, ['camilo', 'andres', 'felipe'],
    indice = nombres.indexOf('andres');
if(indice > -1){
  nombres.splice(index, 1);//[
  //Aquí se debe guardar el arreglo nuevamente en el localStorage.
}

I recommend that you modify the objects that you are saving, and index them, something like this:

var personas = [{id: 1, nombre: 'Camilo'}, {id: 2, nombre: 'Andrés'}];

This in order to facilitate accessibility to objects, since names may contain special characters such as accents. I hope it is useful for you. To perform the element search and obtain an index you must go through the array and verify the id or use the findIndex function (available for ES2016 / ES6) like this:

var indice = personas.findIndex(persona => persona.id == 1);
//Ejecutar verificación y splice.

I hope it's useful for you.

Edition 1

To obtain the data of an input element you must do the following:

html:

<input type='text' id='nombrePersona' />

js (trigger in click event):

var personas = [{id: 1, nombre: 'Camilo'}, {id: 2, nombre: 'Andrés'}],
    inputRefValue = document.getElementById('nombrePersona').value,//Obtienes el valor del input
    nuevaPersona = {id: xx, nombre: inputRefValue};
personas.push(nuevaPersona); //Después de esto debes guardar en el localStorage

You must bear in mind that the id that you are going to put in the new person can not exist in the arrangement of the people that are in the local storage. A good practice is to use some combination of characters and the timestamp.

    
answered by 25.04.2018 в 18:09