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

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')
})
}

Related

Does anyone know how I can store those in localStorage?

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"));

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>

convert json data to pdf using jQuery

I want to export JSON data to pdf with out using any third party plugin.I am having data in Json and need to display data in pdf table structure using JQuery. Please let me know if its possible.
Here is sample JSON
jsonResult.Products[
{PRODUCT_ID: 123, PRODUCT_NUMBER: "00022", PRODUCT_NAME: "HONDA", PRODUCT_TYPE: "VEHICLE "},
{PRODUCT_ID: 783, PRODUCT_NUMBER: "08412394", PRODUCT_NAME: "HONDA", PRODUCT_TYPE: "MOTOR "}.....]
Code snippet using jS PDF-autotable
<script src="~/Scripts/JsPDF-Autotable.js"></script>
$("#btnExportPDF").click(function () {
let table = document.createElement('table');
table.setAttribute("id", "pdfTable");
let thead = document.createElement('thead');
let tbody = document.createElement('tbody');
let thead_tr = document.createElement('tr');
let sample = dataResult.Cases[0];
let columns = [];
let columnData = [];
for (let column in sample) columns.push(column);
for (let i = 0; i < columns.length; i++) {
let th = document.createElement('th');
th.innerText = columns[i];
thead_tr.appendChild(th);
}
thead.appendChild(thead_tr);
for (let i = 0; i < dataResult.Cases.length; i++) {
let tr = document.createElement('tr');
let product = dataResult.Cases[i];
for (let column = 0; column < columns.length; column++) {
let td = document.createElement('td');
td.innerText = product[columns[column]];
columnData.push(product[columns[column]]);
tr.appendChild(td);
}
tbody.appendChild(tr);
}
table.appendChild(thead);
table.appendChild(tbody);
var doc = new jsPDF('p', 'pt');
doc.autoTable(columns, columnData)
doc.save("table.pdf");
});
I tried to export to pdf using jspdf autotable and I am getting below error
JsPDF-Autotable.js:1538 Use of deprecated autoTable initiation
Yes it's definitely possible.
The process is very simple:
Prepare your JSON data
Create a table element filled with your data
Export table with JSPDF
Creating the table
let table = document.createElement('table');
let thead = document.createElement('thead');
let tbody = document.createElement('tbody ');
let thead_tr = document.createElement('tr');
let sample = jsonResult.Products[0];
let columns = [];
for (let column in sample) columns.push(column);
for (let i = 0; i<columns.length;i++){
let th = document.createElement('th');
th.innerText = columns[i];
thead_tr.appendChild(th);
}
thead.appendChild(thead_tr);
for (let i = 0; i<jsonResult.Products.length;i++){
let tr = document.createElement('tr');
let product = jsonResult.Products[i];
for (let column = 0; column < columns.length; column++){
let td = document.createElement('td');
td.innerText = product[columns[column]];
tr.appendChild(td);
}
tbody.appendChild(tr);
}
table.appendChild(thead);
table.appendChild(tbody);
document.body.appendChild(table); // Now this is your table which you are going to export
Follow this SO answer/guide to export the HTML table with JSPDF

Creating dynamically large table using JavaScript

I'm trying to create dynamically a table using JavaScript.
Here is the code I'm using (or here http://liveweave.com/mqG5iT):
function Process(){
CreatTable(['First Name', 'Last Name', 'Email']);
}
function CreatTable(data) {
var checkbox;
var table;
var thead;
var tr;
var th;
var tbody;
tablearea = document.getElementById('ShowDataID');
table = document.createElement('table');
table.id = "ContactsTable";
thead = document.createElement('thead');
tr = document.createElement('tr');
tbody = document.createElement('tbody');
//create columns input checkbox column
checkbox = CreateHTMLElement("chkBoxAllEmails", "chkBoxAllEmails", "SelectAllEmails()", "checkbox", "false");
th = document.createElement('th');
th.appendChild(checkbox);
tr.appendChild(th);
thead.appendChild(tr);
//create columns FirstName,LastName,Emails
for (var i = 0; i < data.length; i++) {
var headerTxt = document.createTextNode(data[i]);
th = document.createElement('th');
th.appendChild(headerTxt);
tr.appendChild(th);
thead.appendChild(tr);
}
table.appendChild(thead);
//create rows and addind to table
for (var i = 0; i < 2000; i++) {
tr = document.createElement('tr');
checkbox = CreateHTMLElement("11", "11", "11", "checkbox", "11");
tr.appendChild(document.createElement('td'));
tr.appendChild(document.createElement('td'));
tr.appendChild(document.createElement('td'));
tr.appendChild(document.createElement('td'));
tr.cells[0].appendChild(checkbox); tr.cells[1].appendChild(document.createTextNode('John'+i.toString()));
tr.cells[2].appendChild(document.createTextNode('McDowell'));
tr.cells[3].appendChild(document.createTextNode('ddd#gmail.com'));
tbody.appendChild(tr);
table.appendChild(tbody);
}
document.getElementById("TablePagingArea").appendChild(table);
//return table;
}
function CreateHTMLElement(id, name, onclick, type, value) {
var HTMLElement = document.createElement('input');
HTMLElement.id = id;
HTMLElement.name = name;
HTMLElement.onclick = onclick;
HTMLElement.type = type;
HTMLElement.value = value;
return HTMLElement;
}
With a small set of data 1000-3000 rows it works relatively well but, some of the data set contains upwards of 5000 rows which causes Firefox to crash and close or become unresponsive.
My question is: is there a better way to accomplish what I am trying to do?
Most efficient way to create a bunch of elements is to create a string and create element from this string.
Most efficient way to create a string of element is to join from array
So you should refactor your code to
Create an array of elements like a[i] = "<tr><intput type='checkbox'></tr>";
Join an array to get one string var s = a.join();
Create DOM elements like var div = document.createElement('div'); div.innerHTML = s;

Categories

Resources