insert and retrieve from local storage - javascript

i'm trying to insert data as array to local storage and retrieve all data on an table
but i have two problems
the first is when i insert it on local storage all data stores as a one array with multiple values
<script type="text/javascript">
var arr= [];
function insert(){
var fname = document.getElementById('fname').value;
var email = document.getElementById('email').value;
var pass = document.getElementById('pass').value;
var phone = document.getElementById('number').value;
Array.prototype.push.apply(arr, [fname,email,pass,phone]);
var pval="";
for(i=0; i<4; i++){
arr[i];
}
let myobj =JSON.stringify(arr);
localStorage.setItem('arr', myobj);
}
</script>
and im trying to display the data on a table in different page but .it shows non
<script type="text/javascript">
function addRow(){
name = localStorage.getItem("fname");
email = localStorage.getItem("email");
password = localStorage.getItem("pass");
phone = localStorage.getItem("number");
var table = document.getElementsByTagName('table')[0];
var newRow = table.insertRow(1);
var cell1= newRow.insertCell(0);
var cell2 = newRow.insertCell(1);
var cell3 = newRow.insertCell(2);
var cell4 = newRow.insertCell(3);
cell1.innerHTML = name;
cell2.innerHTML = email;
cell3.innerHTML = password;
cell4.innerHTML = phone;
}
</script>
what is the problem?

localStorage.setItem('arr', myobj) // here the local storage is set
You only set an item called arr into the local storage. This item is a json which represents the array you parsed before.
const json = localStorage.getItem("arr");
const obj = JSON.parse(arr)
console.log(obj)
This way you can get the original object from the storage.

Related

How do I can get back the value of these table cells?

I got this function for a CRUD to receive some data and charge it to the html:
async function loaded() {
let data = await getRequest('http://localhost/ALMACEN/Backend/get.php');
document.getElementById("imagen").innerHTML =
'<img src="Front-End/imagenes/' + data.data[0].prod_img + '" width="50%"; height= "auto";>';
for (var i = 0; i < data.data.length; i++) {
var table = document.getElementById("employeeList").getElementsByTagName('tbody')[0];
var newRow = table.insertRow(table.length);
cell1 = newRow.insertCell(0);
cell1.innerHTML = data.data[i].prod_nombre;
cell2 = newRow.insertCell(1);
cell2.innerHTML = data.data[i].prod_precio;
cell3 = newRow.insertCell(2);
cell3.innerHTML = data.data[i].prod_cantidad;
cell4 = newRow.insertCell(3);
cell4.innerHTML = `&#129089
&#129087
Borrar`;
}
}
I wanna get back the values to make the Delete button work, what can I do?
Add the key fields to data attributes on the button for easy access:
Borrar`;
Then in JS:
$(".delete-button").on("click", function() {
var id = $(this).data("id");
});
If you're generating the elements dynamically, you might need to bind the click event to the document instead of the button.
You can use any and multiple data attributes: data-uid, data-name, etc.
using jquery you can use this
$('#employeeList').on('click', '.opis', function(e){
e.preventDefault();
var fila=$(this).closest('tr');
var name= fila.find("td:eq(0)").text();
alert("name: "+name);
$("#name").html(name);
})

javascript dom conflict: how to start at column 2

My JavaScript DOM model is conflicting. I have an exporttable who on one side generate an indexnumber and on the other side imports data (firsName, lastName and points from an importform. I try to get the indexnumber on column 1, firstName in 2, lastName in 3 and points in 4.
At this moment indexnumber is in column 1(good) but firstName starts in column 1 too (not good). If adding (see script) newRow.insertCell(1); the console protests.
Who can help me?
<script>
var button3 = document.getElementById("button2");
button3.onclick= addData;
function addData() {
// collect data firstname, lastname, points
var firstName = document.getElementById("firstname");
var lastName = document.getElementById("lastname");
var Points = document.getElementById("points");
var exportTable = document.getElementById("exportTable");
var newRow = exportTable.insertRow(-1);
var cel1 = newRow.insertCell(0); //I can not start here with insertCell(0);
var cel2 = newRow.insertCell(1);
var cel3 = newRow.insertCell(2);
cel1.innerHTML = firstName.value;
cel2.innerHTML = lastName.value;
cel3.innerHTML = Points.value;
//instal number
var amountRows = exportTable.rows.length;
for (var i = 1; i < amountRows; i++) {
exportTable.rows[i].children[0].innerHTML = i;
}
}
</script>

keep javascript variables values obtained by id after refresh

i'm getting some html input values with javascript that i insert in a table , but those turned null when i refresh , how can i keep those value visible after refresh . I know i should set and get my cookies but i just don't how .
here is my javascript code :
function myFunction(tableID) {
var x = document.getElementById("name").value;
var ad = document.getElementById("address").value;
var nu = document.getElementById("tel").value;
var pr = document.getElementById("product").value;
var s = document.getElementById("size").value;
var d = document.getElementById("date").value;
var st = document.getElementById("statu").value;
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
cell1.innerHTML = x;
var cell2 = row.insertCell(1);
cell2.innerHTML = ad;
var cell3 = row.insertCell(2);
cell3.innerHTML = nu;
var cell4 = row.insertCell(3);
cell4.innerHTML = pr;
var cell5 = row.insertCell(4);
cell5.innerHTML = s;
var cell6 = row.insertCell(5);
cell6.innerHTML = d;
var cell7 = row.insertCell(6);
cell7.innerHTML = st;
}
any help ?
THanks
One way to do it would be to stick them in sessionStorage (which will be accessible across page refreshes).
To store them:
sessionStorage.setItem('foo', 'bar');
to get them:
sessionStorage.getItem('foo');
When your page is loaded, you can get them from the sessionStorage to repopulate your elements.
you can use localStorage
// before you leave your page , save all your variables here
window.onunload = function(){
// save them one by one in to localStorage
localStorage.setItem("x", x)
...
}
when you enter the page load from localStorage first :
// before all your code work.
window.onload = function (){
// set value back one by one
document.getElementById("name").value = localStorage.getItem("x");
...
}

Retrieve a variable value from a table cell in javascript

How do I retrieve a variable value from a table cell using javascript.
var clicks = new Array();
var click1;
var click2;
function addTableRow() {
click1 = parseInt(document.getElementById('caption').value),10;
click2 = parseInt(document.getElementById('caption1').value),10;
var clicks = [click1, click2];
clicks.push({c1:clicks[0], c2:clicks[1]});
var table = document.getElementById('table');
var row = table.insertRow(-1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
var input = document.createElement('input');
input.setAttribute("type", "text");
input.style.width = "100px";
cell2.appendChild(input);
cell3.innerHTML = "x:" + clicks[0] + ", y:" + clicks[1];
var btnDelete = document.createElement('Button');
var btnDeleteText = document.createTextNode("Delete");
btnDelete.appendChild(btnDeleteText);
btnDelete.style.width = "80px";
cell4.appendChild(btnDelete);
btnDelete.onclick = function() {
var rowToDelete = this.parentNode.parentNode;
var parentReference = rowToDelete.parentNode;
parentReference.removeChild(rowToDelete);
var inputsInTable = document.getElementsByTagName('input');
for(i=0; i<inputsInTable.length; i++)
{
??????????????????????
}
}
}
Basically, when I add a row the clicks get stored in the array. When I delete a row, I need to update the array by rebuilding it.
I hope it's more clear now.
Any help would be very appreciated.
Marco

Is there a way to transfer an object from one local storage to another local storage?

I am trying to move an object from one localStorage to another localStorage based on whether or not a checkbox in a table is ticked.
// version 1.0
// Developer
// Date: Tuesday December 29th 2015
// Registeration for Cars and stuff as well as table to retreive the Car information
var Car = [];
function carReg(storagekey) {
alert('submitted');
"use strict";
// checks localstorage to see if there are already values and then keeps those values rather than deleteing them
//Car = JSON.parse(localStorage.getitem(storagekey));
// if (Car == null) {
// Car = [];
// }
// push all of the data into localStorage under the specific variable id's
Car.push({
Brand: document.getElementById("mySelect").value,
Model: document.getElementById("selectModel").value,
Age: document.getElementById("carAge").value,
KM: document.getElementById("km").value,
Name: document.getElementById("name").value,
ContactInfo: document.getElementById("cInfo").value,
})
// stores everthing into local storage under the specified key
localStorage.setItem(storagekey, JSON.stringify(Car))
}
/////////////////////////////
/// Table Code starts here//
///////////////////////////
function maketable() {
// get data from localStorage
var carReg = JSON.parse(localStorage.getItem("register"))
// Variables for the table values and classifications
var table, row, cell1, cell2, cell3, cell4, cell5, cell6;
table = document.getElementById('ownedCar')
// Row definers
for (var index = 0; index < carReg.length; index++) {
var checkbox = document.createElement('input');
checkbox.type = "checkbox";
checkbox.id = index;
row = table.insertRow(index+1)
cell1 = row.insertCell(0);
cell2 = row.insertCell(1);
cell3 = row.insertCell(2);
cell4 = row.insertCell(3);
cell5 = row.insertCell(4);
cell6 = row.insertCell(5);
cell7 = row.insertCell(6);
// row classifications
cell1.innerHTML = carReg[index].Brand
cell2.innerHTML = carReg[index].Model
cell3.innerHTML = carReg[index].Age
cell4.innerHTML = carReg[index].KM
cell5.innerHTML = carReg[index].Name
cell6.innerHTML = carReg[index].ContactInfo
cell7.appendChild(checkbox);
}
}
function selling() {
//query from localStorage
var carReg = JSON.parse(localStorage.getItem("register"))
for (var index = 0; index < carReg; index++) {
if (!(document.getElementById(index).checked)) {
index = localStorage.setItem("sell", JSON.stringify(carReg))
}
}
}
Basically the part that should be doing this is this.
function selling() {
//query from localStorage
var carReg = JSON.parse(localStorage.getItem("register"))
for (var index = 0; index < carReg; index++) {
if (!(document.getElementById(index).checked)) {
index = localStorage.setItem("sell", JSON.stringify(carReg))
}
}
}
But it isn't doing anything. Is there something that I'm missing? Or is it just that my if statement part is wrong?
I found what the answer was I was missing a '.length' in my for statement. Thanks wapsee!

Categories