Does anyone know how I can store those in localStorage? - javascript

const tr = document.createElement("tr");
const td = document.createElement("td");
table.appendChild(tr);
td.innerText = "" + new Date().toLocaleDateString("de-Ch");
tr.appendChild(td);
const td2 = document.createElement("td");
td2.innerText = object.text;
tr.appendChild(td2);
const td3 = document.createElement("td");
if (object.amount > 0){
td3.style.color = "rgb(4, 209, 4)";
td3.innerText = "+";
} else{
td3.style.color = "red";
}
td3.innerText += object.amount;
tr.appendChild(td3);
const td4 = document.createElement("td");
td4.style.color = saldo < 0 ? "red" : "black";
td4.innerText = saldo.toFixed(2);
tr.appendChild(td4);
Basically this code gets ran when I submit a form and it adds a tr and td's to a table which I already have as elementById. My question is, does anyone know how I could store the values, that I input, as localStorage, so that when I refresh, the table with the different rows stays as before and that I can still add more rows? I'd be very thankful for an answer. If there's more information about the code needed, I'd be happy to provide it.

You can create an object array and add it in localStorage if it is not available.
var objectArray = [];
localStorage.setItem("objectArray", JSON.stringify(objectArray))
Add objects to the array when form is submitted and update localStorage.
var objectArray = JSON.parse(localStorage.getItem("objectArray"));
objectArray.push(object);
localStorage.setItem("objectArray", JSON.stringify(objectArray));
update the table with new rows based on the objects available in the array.
var objectArray = JSON.parse(localStorage.getItem("objectArray"));

Related

Define specific xml children

I have an xml feed of products:
https://feedfiles.woolytech.com/loja-domot.myshopify.com/domot_feed.xml
I'm getting problems trying to make a condition like this, when class name(from the XML) = price then this variable return the price.
I could get the values when I specified like productsXmlNode.children[4].innerHTML; but the 4th class is not the same for every product. so I want to define the class by the name and not by the number.
I will show the code above.
<script>
// first get the reference to the h1 tag
const h1 = document.querySelector("h1");
// using classList property
const h1ClassNames = h1.classList;
console.log(h1ClassNames);
let xmlContent = '';
let tableProducts = document.getElementById('entry');
fetch('produtos_domot_feed.xml').then((response)=> {
response.text().then((xml)=>{
xmlContent = xml;
let parser = new DOMParser();
let xmlDOM = parser.parseFromString(xmlContent, 'application/xml');
let products = xmlDOM.querySelectorAll('entry');
products.forEach(productsXmlNode => {
let row = document.createElement('tr');
//author (brand)
let td = document.createElement('td');
td.innerText = productsXmlNode.children[4].innerHTML;
row.appendChild(td);
// title
td = document.createElement('td');
td.innerText = productsXmlNode.children[2].innerHTML;
row.appendChild(td);
//price
td = document.createElement('td');
td.innerText = productsXmlNode.children[2].innerHTML;
row.appendChild(td);
//description
td = document.createElement('td');
td.innerText = productsXmlNode.getElementsByClassName('g:price').innerHTML;
row.appendChild(td);
//image
td = document.createElement('td');
td.innerText = productsXmlNode.children[3].innerHTML;
row.appendChild(td);
tableProducts.children[1].appendChild(row);
});
});
});
</script>
</body>
</html>

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>

table won't allow me to append more than 2 cells

function createTable(data_array){
const billing_table_body = document.querySelector('#billing_progile_Table > tbody')
//we loop through object array and have access to each individual JSON
for(var i = 0; i<objarray.length;i++){
console.log("data : ",objarray[i].profileName)
//create row
const tr = document.createElement('tr'); //creating the row
console.log('creating new row');
//append individual tds
const td = document.createElement('td')
td.textContent = objarray[i].profileName//appends data from the json cell
td.className = 'text_td';
tr.appendChild(td);
const td_two = document.createElement('td')
td_two.textContent = objarray[i].cardemail
td.className = 'text_td';
tr.appendChild(td_two);
const td_three = document.createElement('td')
td_two.textContent = objarray[i].cardownername
td.className = 'text_td';
tr.appendChild(td_three);
const td_four = document.createElement('td')
td_two.textContent = objarray[i].cardnumber
td.className = 'text_td';
tr.appendChild(td_four);
//append whole row to tr
billing_table_body.appendChild(tr);
}
}
im trying to append the cells into the table with their data but the table won't allow me to do it and I need to write it like this because im trying to access specific objects of the json array. any help im new to JAVASCRIPT AND JSON
Please stop adding row and cells with createElement() method...!
const billing_table_body = document.querySelector('#billing_progile_Table > tbody')
function createRows(data_array)
{
data_array.forEach(el =>
{
let newRow = billing_table_body.insertRow()
newRow.insertCell().textContent = el.profileName
newRow.insertCell().textContent = el.cardemail
newRow.insertCell().textContent = el.cardownername
newRow.insertCell().textContent = el.cardnumber
newRow.querySelectorAll('td').forEach(td=>td.className='text_td')
})
}

Adding class name or id to Table with JS

Suppose this code to create a table with plain JavaScript using DOM (Fiddle):
var table = document.createElement('table');
for (var i = 1; i < 4; i++){
var tr = document.createElement('tr');
var td1 = document.createElement('td');
var td2 = document.createElement('td');
var text1 = document.createTextNode('Text1');
var text2 = document.createTextNode('Text2');
td1.appendChild(text1);
td2.appendChild(text2);
tr.appendChild(td1);
tr.appendChild(td2);
table.appendChild(tr);
}
document.body.appendChild(table);
How can I add a class name or an id to its cells?
For example I want to be able to modify cells after their creation, so I want just :
table.getElementsByClassName("class").style.font-weight: "bold";
Use HTML DOM setAttribute() Method to add attributes to an element, like following :
var td1 = document.createElement('td');
var td2 = document.createElement('td');
td1.setAttribute('class', 'className');
td2.setAttribute('class', 'className');
Hope this helps.
Do:
table.setAttribute("id", "myId");
Read up: MDN Element.setAttribute()
Use the same function to set class, just like #Zakaria mentioned.

JavaScript/DOM - Give a newly created element an ID

How can I apply an element ID to a newly created element through JavaScript DOM?
The code I have written creates a table which is triggered from a button.
I need to apply a unique ID to this table so it can be styled differently to others which appear on my site.
Here is a sample of my code:
var tab = document.createElement("ViewShoppingCart");
document.getElementById("shopping_list").appendChild(tab);
var tbdy = document.createElement("tbody");
tab.id = "new_cart";
tab.appendChild(tbdy);
new_cart = true;
var total = 0;
for (var a = 0; a <= nameArray.length-1; a++) {
var tr = document.createElement("tr");
tbdy.appendChild(tr);
var td = document.createElement("td");
td.appendChild(document.createTextNode("x " + quantityArray[a]));
tr.appendChild(td);
var td2 = document.createElement("td");
td2.appendChild(document.createTextNode(nameArray[a]));
tr.appendChild(td2);
var td3 = document.createElement("td");
td3.appendChild(document.createTextNode(sumArray[a]));
tr.appendChild(td3);
}
Try
var tbdy = document.createElement("tbody");
tbdy.id = "newtbodyid";
tab.id = "new_cart";
tab.appendChild(tbdy);
new_cart = true;
For applying styles consider using class selectors, you may not need IDs at all.
Note that if you want to create valid HTML you can't have duplicated IDs that significantly lessens value for CSS styles, especially for table data.

Categories

Resources