Using json array to populate html table - javascript

I am using local storage to save an object. I am having troubles than using this object to populate a table. Right now the object is showing up as an array in the third column. How can I use the json array to fill column 1, column 2 and column 3 with the value, key and image from the object.
$(document).on('click', '[data-toggle=add]', function() {
var latlng = $(this).data('latlng');
var address = $(this).data('address');
var image = $(this).data('image');
var key = $(this).data('id');
var testObject = {
'latlng' : latlng,
'address' : address,
'image' : image
};
localStorage.setItem(key, JSON.stringify(testObject));
updateTable();
});
function updateTable() {
var tbody = document.getElementById("output");
while(tbody.getElementsByTagName("tr").length > 0) {
tbody.deleteRow(0);
}
var row;
if(localStorage.length == 0) {
row = tbody.insertRow(i);
cell = row.insertCell(0);
cell.colSpan = "4";
cell.innerHTML = "Nothing to Show";
}
for(var i = 0; i < localStorage.length; ++i) {
row = tbody.insertRow(i);
cell = row.insertCell(0);
cell.innerHTML = i;
cell = row.insertCell(1);
cell.innerHTML = localStorage.key(i)
cell = row.insertCell(2);
cell.innerHTML = localStorage.getItem(localStorage.key(i));
cell = row.insertCell(3);
cell.innerHTML = '<button class="btn btn-danger btn-sm" onclick="deleteItem(\'' + localStorage.key(i) + '\');"><i class="fa fa-trash-o"></i> Delete</button>';
}
}

You haven't posted all your markup but I believe this is your problem:
You are not retreiving the localStorage correctly. You are saving a stringified version of a JSON object and then you are trying to access it directly as an object.
Instead, you need to retrieve the localstorage item and parse it back to a JSON object, then iterate through it or access its properties as an object.
Replace:
cell.innerHTML = localStorage.key(i);
With:
json = JSON.parse(localStorage.key(i));
cell.innerHTML = json.latlng;// or json.address or json.image;
Hope this helps!

Related

While displaying its also print old Data from local storage

function addrow() {
debugger;
var person = [];
if (localStorage.person1 != null && localStorage.person1 !=undefined) {
var person = JSON.parse(localStorage.person1);
}
var name = document.getElementById('name').value;
var city = document.getElementById('city').value;
person.push({
pname: name,
pcity: city
});
localStorage.setItem('person1', JSON.stringify(person));
bind();
}
function bind() {
debugger;
var per_list = JSON.parse(localStorage.getItem('person1'));
for (i = 0; i < per_list.length; i++ ) {
var table = document.getElementById('ptable');
var row = table.insertRow(0);
var col1 = row.insertCell(0);
var col2 = row.insertCell(1);
col1.innerHTML = per_list[i].pname;
col2.innerHTML = per_list[i].pcity;
}
}
I have two fields name and city;Now, click on "add row" prints ok for first value, but afterwards it is printing both old and new value.. And, i want only new entry below the old input.. thanks in advance
You need to clear the table since you are showing all the elements in the .bind function.
function bind() {
debugger;
var per_list = JSON.parse(localStorage.getItem('person1'));
// clear the table
var table = document.getElementById('ptable');
for (var i = 0, rows = table.rows.length; i < rows; i++) {
table.deleteRow(0)
}
// fill the table
for (i = 0; i < per_list.length; i++) {
var row = table.insertRow(0);
var col1 = row.insertCell(0);
var col2 = row.insertCell(1);
col1.innerHTML = per_list[i].pname;
col2.innerHTML = per_list[i].pcity;
}
}

Reorder table using js when add more row in the table

I create a table from a JS to add more row
function addItem(code,name) {
var tblList = document.getElementById("list_inventory");
var tblBody = tblList.tBodies[0];
var lastRow = tblBody.rows.length;
var row = tblBody.insertRow(lastRow);
var newCell = row.insertCell(0);
newCell.innerHTML = lastRow+1;
var newCell = row.insertCell(1);
newCell.innerHTML = name+"<input type='hidden' name='code[]' id='code[]' value='"+code+"' />";
}
But the problem is I need to make a table ascending by 'name' whenever I create more row? Is it possible?
Of course it's possible. After you inserted:
var rows = tblBody.rows;
rows.sort(function(a,b) {
var first = a.cells[0].children[0].name;
var second = b.cells[0].children[0].name;
return (first.name < second.name) ? 1 : ((first.name > second.name) ? -1 : 0);
});
tblBody.rows.innerHTML = rows;
So the idea is to pick the rows and then sort it by input name prop. Hope it'll help you.

javascript multiple array into json

How to get each table row and its respective inputs (checkbox, text, select) into an array to store in localstorage? I've complete most of the code, the part I need to build is the ???? part. Thanks.
This is the javascript code:
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for(var i=0; i<colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[0].cells[i].innerHTML;
}
}
$('#btnSave').on('click', function(e) {
e.preventDefault();
var id = $(this).attr("data-id");
var mykey = 'set'+id;
// here just to check whether 'set'+id exist or not, no validation performed
if(localStorage.getItem(mykey)==null){
console.log('key not found');
} else {
console.log('key found');
}
// Due to there will be one or more rows,
// need to loop the rows and get the inputs within
// and store them in localstorage
$('#dyn_table tr').each(function(){
var tr = $(this);
var checkbox = $(this).find('.big-checkbox').is(':checked');
var itemcode = $(this).find('.dyn_item_code :selected').val();
var amount = $(this).find('.dyn_amount').val();
var reference = $(this).find('.dyn_reference').val();
console.log(checkbox);
console.log(itemcode);
console.log(amount);
console.log(reference);
});
localStorage.setItem(mykey, ????);
});
This is the input button if you wonder how i dynamically generate the table row
<input type="button" value="Add row" onClick="addRow('dyn_table')" />
Create an array of objects.
var array = [];
$('#dyn_table tr').each(function(){
var tr = $(this);
var checkbox = $(this).find('.big-checkbox').is(':checked');
var itemcode = $(this).find('.dyn_item_code :selected').val();
var amount = $(this).find('.dyn_amount').val();
var reference = $(this).find('.dyn_reference').val();
array.push({
checkbox: checkbox,
itemcode: itemcode,
amount: amount,
reference: reference
});
console.log(checkbox);
console.log(itemcode);
console.log(amount);
console.log(reference);
});
localStorage.setItem(mykey, JSON.stringify(array));
I didn't know if I understood your problem but this is working ?
var my_table = [] // Create an array for the table
$('#dyn_table tr').each(function(){
var tr = $(this);
var checkbox = $(this).find('.big-checkbox').is(':checked');
var itemcode = $(this).find('.dyn_item_code :selected').val();
var amount = $(this).find('.dyn_amount').val();
var reference = $(this).find('.dyn_reference').val();
// For each row, create a item on the array, containing all important data for the row
my_table.push({checkbox, itemcode ,amount, reference})
});
console.log("My table :", my_table)
localStorage.setItem(mykey, JSON.stringify(my_table));
If you don't want to save each col like: {checkbox: true, itemcode: 'foo', ...} but have an ordered array instead, you can replace the new line by:
my_table.push([checkbox, itemcode ,amount, reference])

How to read values from a Firebase Database and store them into an HTML table

I have a Firebase Database that stores two values distance and a timestamp. I'm able to read the distances, but un able to read to more than 1 timestamp at a time.
for (var i = 0; i <= 10; i++) {
ref.child("distance").child(i).once("value").then(function(snapshot) {
test = snapshot.val();
test1 = JSON.stringify(test).replaceAll(/[^a-zA-Z0-9.]/g, "");
myCreateFunction(test1, i+"");
});
ref.child("time").child(i).once("value").then(function(snapshot) {
time1 = snapshot.val();
console.log(time1);
myCreateFunc(time1["0"], i+"");
});
}
function myCreateFunction(test1, i) {
var table = document.getElementById("myTable");
var row = table.insertRow(-1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell2.id = i;
cell1.innerHTML = test1;
}
function myCreateFunc(time1, i) {
document.getElementById(i).innerHTML = time1;
}
This is a picture of my database
This is the picture of the error that we get on our webpage
I think you are only sending your first element of the array to the HTML create table:
myCreateFunc(time1["0"], i+"");
instead of something like this:
myCreateFunc(time1, i+"");
Let me know if this solved your problem!

Accessing HTML Table Cell Data

I need to access to the data of a html cell,but before that ,I need to store the id of my array (details[i].id) in a cell. I tried with a hidden, but I get an empty cell when I show the table and that's not what I want, what I want is something like the DataKeyNames in ASP.net, that gives us the chance to store the id without necessarily showing it.
This is the code I use to show my array (details) in a html table:
function showTable()
{
if (details.length>0){
for (var i=0; i<details.length;i++)
{
var tbl = document.getElementById('myTable');
var newRow = tbl.insertRow(tbl.rows.length);
var cell1 = newRow.insertCell(0);
cell1.textAlign='center';
cell1.innerHTML=details[i].price;
var cell2 = newRow.insertCell(1);
cell2.textAlign='center';
cell2.innerHTML=details[i].description;
var cell3 = newRow.insertCell(2);
cell3.textAlign='center';
cell3.innerHTML='<img src="images/delete.png" width="14" height="14" alt="Delete" onclick="removeDetail(this)"/>'
}
}
}
And finally in the removeDetail function is where I need to get the cell value, assuming I somehow put the id there.
function removeDetail(r)
{
var node = r.parentNode;
while( node && node.tagName !== 'TR' ) {
node = node.parentNode;
}
var i=node.rowIndex;
document.getElementById('myTable').deleteRow(i);
//here's where I need to get the id and, if posible the other values ( price, description) too.
}
Hope you can help me out.
First step: store the index as custom attribute of your element:
cell3.innerHTML='<img src="images/delete.png" width="14" height="14" alt="Delete" onclick="removeDetail(this)" details_index="' + i + '" />'
Second step: store the row as part of the global array:
details[i].row = newRow;
Final step: In the removeDetail function read the index and you have all you need:
function removeDetail(r)
{
var item = details[parseInt(r.getAttribute("details_index"), 10)];
item.row.style.display = "none";
alert("price: " + item.price + ", description: " + item.description);
}
Try below code :
function checkSequence()
{
var oTable = document.getElementById('tableID');
var rowLength = oTable.rows.length;
var count=0;
for (i = 0; i<rowLength-1; i++){
var cellVal = document.getElementById('tableID:'+i).value;
}
}

Categories

Resources