local storage table - javascript

i am storing my values into a local storage, and i am trying to display the information in a table, but it doesnt seem to work and it always outputs it into the first column go down vertically.
for example i want it to come out like this when i enter my information
|Balance|Name|Quantity|Price|
| 100 |test| 100 | 1.99|
but instead it is currently displaying like this:
|Balance|Name|Quantity|Price|
|100|
|test|
|100|
|1.99|
This is the code for my local storage
function save(item) {
var playlistArray = getStoreArray("playlist");
playlistArray.push(item);
localStorage.setItem("playlist", JSON.stringify(playlistArray));
}
function Load_storage() {
var playlistArray = get_Storage();
var ul = document.getElementById("playlist");
if (playlistArray != null) {
for (var i = 0; i < playlistArray.length; i++)
{
var li = document.createElement("table");
li.innerHTML = playlistArray[i];
ul.appendChild(li);
}
}
}
function get_Storage() {
return getStoreArray("playlist");
}
function getStoreArray(key) {
var playlistArray = localStorage.getItem(key);
if (! playlistArray) {
playlistArray = new Array();
}
else {
playlistArray = JSON.parse(playlistArray);
}
return playlistArray;
}
And i put into my local storage via this function
var table=document.getElementById("myTable");
var row=table.insertRow(1);
var cell1=row.insertCell(0); // bank account
var cell2=row.insertCell(1); // name
var cell3=row.insertCell(2); // Quantity
var cell4=row.insertCell(3); // price
cell1.innerHTML=Balance ; // bank account
cell2.innerHTML=name; //stock symbol
cell3.innerHTML=quantity; // Quantity
cell4.innerHTML=price; // bought
var SAVE= document.getElementById("myTable");
SAVE.appendChild(row);
save(cell1.innerHTML);
save(cell2.innerHTML);
save(cell3.innerHTML);
save(cell4.innerHTML);
// save(Balance+"......................."+
name+"......................."+
quantity+"......................."+
price + ".......................");
this is commented out because it will always show the line but i dont want it that way even tho this way does work

Put the table column headers in your html. It is much more efficient than doing it with JavaScript:
<body>
<table id='myTable'>
<thead>
<tr>
<th>Balance</th>
<th>Name</th>
<th>Quantity</th>
<th>Price</th>
</tr>
</thead>
</table>
</body>
Some changes to your JavaScript:
var table = document.getElementById("myTable"),
row = table.insertRow(1),
cell1 = row.insertCell(0), // bank account
cell2 = row.insertCell(1), // name
cell3 = row.insertCell(2), // Quantity
cell4 = row.insertCell(3), // price
testBalance = '3.00',
testName = 'Mike',
testQuantity = '2.00',
testPrice = '5.00';
cell1.innerHTML = testBalance; // bank account
cell2.innerHTML = testName; //stock symbol
cell3.innerHTML = testQuantity; // Quantity
cell4.innerHTML = testPrice; // bought
//you can remove these lines
//var SAVE = document.getElementById("myTable");
//SAVE.appendChild(row);
save(cell1.innerHTML);
save(cell2.innerHTML);
save(cell3.innerHTML);
save(cell4.innerHTML);
// save(Balance+"......................."+
// name + "......................." +
// quantity + "......................." +
//price + //".......................");
Here is a jsFiddle.
I hope this helps :-)

Related

I want to set information to localstorage

playlist = [];
//저장
function save() {
localStorage.setItem("playlist",JSON.stringify(playlist));
}
// 리스트 생성
$('td#btn-add-row').click(function() {
// id 구하기
var list_num = 1;
for(var i=1; i <= 100; i++ )
{
if ( $('#basic tr td:nth-child(1)').hasClass(String(i)) == false )
{
list_num = i; break;
}
}
// 추가
const tbody = document.getElementById('my-tbody');
const tr = document.createElement("tr");
tr.id = list_num;
const td1 = document.createElement("td");
td1.className = list_num;
td1.setAttribute("style", "cursor:pointer");
const td2 = document.createElement("td");
td2.innerText = "음악 "+list_num;
const td3 = document.createElement("td");
td3.innerHTML = "<input type='text' name='tb'>";
const td4 = document.createElement("td");
td4.innerHTML = "<input type='text'>";
tbody.appendChild(tr);
tr.appendChild(td1);
tr.appendChild(td2);
tr.appendChild(td3);
tr.appendChild(td4);
const data = {
url:$("#my-tbody > tr:nth-child(" + list_num + ")> td> input").val(),
name:$("#my-tbody > tr:nth-child(" + list_num + ")> td:nth-child(4)> input").val(),
id:list_num
}
playlist.push(data);
save();
// 동적 테이블
$("#basic").tableDnD();
});
I wish that URL, name, id are stored in a local storage according to the id value of tr. However, this code produces strange results in localstorage. The problem is that the URL and name are not saved. What should I do?
The reference of a value does not magically keep on updating. So you need to add event listeners to keep updating it. So easiest thing to do is add event listeners to the inputs and update the array of objects.
Below is the basic idea. (note: StackOverflow blocks local storage so I commented it out.)
// const playlist = localStorage.playlist ? JSON.parse(localStorage.playlist) : [];
const playlist = [];
const tableTbody = document.querySelector("#myTable tbody");
for (let i = 0; i < 10; i++) {
// either get the current value from localstorage or create new record
playlist[i] = playlist[i] || {
id: i,
url: '',
name: ''
};
const currentItem = playlist[i]
//create the table row
const tr = document.createElement("tr");
tr.dataset.id = currentItem.id;
// create the id cell
const tdId = document.createElement("td");
tdId.textContent = i + 1;
// create the url cell
const tdUrl = document.createElement("td");
const inputUrl = document.createElement("input");
inputUrl.type = "text";
inputUrl.name = 'url';
inputUrl.value = currentItem.url;
tdUrl.append(inputUrl);
// create the name cell
const tdName = document.createElement("td");
const inputName = document.createElement("input");
inputName.type = "text";
inputName.name = 'name';
inputName.value = currentItem.name;
tdName.append(inputName);
// add the cells to the row
tr.append(tdId);
tr.append(tdUrl);
tr.append(tdName);
// add the row to the table
tableTbody.append(tr);
}
tableTbody.addEventListener("input", function (event) {
// see what triggered the input event
const input = event.target;
// find the row so we know what record to update
const rowId = input.closest("tr").dataset("id");
// what field to update
const field = input.name;
// update the record
playlist[rowId][field] = input.value.trim();
// update local storage
// localStorage.playlist = JSON.stringify(playlist);
});
<table id="myTable">
<thead>
<tr>
<th>ID</th><th>url</th><th>name</th>
</tr>
</thead>
<tbody></tbody>
</table>

Adding new row to table with three columns Javascript html click function

Desrciption
I'd like to able to add a row using javascript with three columns to a table in html.
I am creating a table where the user can enter their own text and add the text along with two other pieces of information to the table into three columns. The current code that I have will not display the new row. The code also includes a drag and drop feature where the user can click on the row and drag it into a different position into the table.
I am asking for guidance as to why when I press the click button it does not add a new row to the table.
edit: Code is now working after update, but the else statement does not do anything.
Javascript
function addRow(mytable) {
var food = document.createTextNode(document.querySelector('.input').value);
var category = document.createTextNode(document.querySelector('.input2').value);
var time = document.createTextNode(document.querySelector('.input3').value);
document.querySelector('.input').value = '';
document.querySelector('.input2').value = '';
document.querySelector('.input3').value = '';
// Get a reference to the table
if (food !== '') {
var tableRef = document.getElementById(mytable);
var attr = document.createAttribute('draggable');
attr.value = 'true';
// Insert a row at the end of the table
var newRow = tableRef.insertRow(-1);
newRow.setAttributeNode(attr);
newRow.className = 'draggable';
// Insert a cell in the row at index 0
var newCell = newRow.insertCell(0);
var newCell2 = newRow.insertCell(1);
var newCell3 = newRow.insertCell(2);
var newText = food;
var newText2 = category;
var newText3 = time;
newCell.appendChild(newText);
newCell2.appendChild(newText2);
newCell3.appendChild(newText3);
addEventsDragAndDrop(newRow);
}
//not working for some reason
else {
document.getElementById("msg").innerHTML = "Please enter a name";
}
}
javascript click
document.getElementById('btn').addEventListener('click', function( {addRow('mytable');});
HTML
<table id="mytable">
<tr>
<th>Component</th>
<th>Category</th>
<th>Time</th>
</tr>
<div id="addRow"></div>
</table>
Few adjustments below, but more detail needed, atm only one text input for component, but can add more for cook/time
function addRow(mytable) {
var newItem = document.createTextNode(document.querySelector('.input').value);
var category = document.createTextNode("Cook");
var time = document.createTextNode("time");
document.querySelector('.input').value = '';
// Get a reference to the table
if (newItem != '') {
var tableRef = document.getElementById(mytable);
var attr = document.createAttribute('draggable');
attr.value = 'true';
// Insert a row at the end of the table
var newRow = tableRef.insertRow(-1);
newRow.setAttributeNode(attr);
newRow.className = 'draggable';
// Insert a cell in the row at index 0
var newCell = newRow.insertCell(0);
var newCell2 = newRow.insertCell(1);
var newCell3 = newRow.insertCell(2);
var newText = newItem;
var newText2 = category;
var newText3 = time;
newCell.appendChild(newText);
newCell2.appendChild(newText2);
newCell3.appendChild(newText3);
addEventsDragAndDrop(newRow);
}
}
document.getElementById('btn').addEventListener('click', function(){addRow('mytable');});
<table id="mytable">
<tr>
<th>Component</th>
<th>Category</th>
<th>Time</th>
</tr>
<tr class="draggable" id="draggable" draggable="true">
<td>Food goes here</td>
<td>Cook</td>
<td>10</td>
</tr>
<div id="addRow"></div>
</table>
<label for='component'>component</label>
<input class='input' id='component' />
<button id='btn'>add component</button>

How to let the user set the table size in HTML?

i want the user to enter the number of rows in a HTML table, how do i do that? this is where is stopped.
var x = prompt("how many rows?");
for ( var count=1)
document.writeln(<tr>)
count++;
{
if (count==x)
break;
}
You code is incomplete and moreover a mess. You wrote for statement without curly braces and the curly braces you put, it way after where it supposed to be.
If you wish to create a row inside a document, at least you need to create a html table first. (You can also do this using JavaScript)
<table>
<tbody>
</tbody>
</table>
Then you can move onto the JS part where user will be asked for input.
Here is a full example.
var x = prompt("how many rows?");
let count = 1;
let table = document.querySelector("table");
for (count = 1; count <= x; count++) {
// insert a row
var row = table.insertRow(0);
// create two cell
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
// default text if you want
cell1.innerHTML = "Cell 1"
cell2.innerHTML = "Cell 2";
}
<table>
<tbody>
</tbody>
</table>
You could do something simple like this:
const inputEl = document.querySelector('#input-el');
const buttonEl = document.querySelector('#button-el');
const divEl = document.querySelector('#table-display');
buttonEl.addEventListener('click', e => {
const rowQty = inputEl.value;
let html = `<table id="tableEl-${rowQty}" border="1">`;
for (let i = 0; i < rowQty; i++) {
html += `<tr><td>${i+1}</td><td>Row ${i + 1}</td></tr>`;
}
html += `</table>`;
divEl.innerHTML = html;
});
<label id="label-el" for="input-el">Number of rows</label>
<input id="input-el" type="text" />
<input id="button-el" type="button" value="Create table" />
<div id="table-display"></div>

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;
}
}

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!

Categories

Resources