The object created every time the submit button is clicked , and it pushed to the book_list array but i get messy when i loop in the list to create a row , how can i solve this ? here is the link : https://jsfiddle.net/s7jmkeqL/
let book = new Book(title.value, authName.value, email.value, price.value, date.value, lang.value, radio.value);
book_list.push(book);
// create new rows
function createTd(content) {
let td = document.createElement('td');
td.appendChild(document.createTextNode(content));
tr.appendChild(td);
table.appendChild(tr);
}
book_list.sort((a, b) => (a.date > b.date) ? 1 : -1); // sort the list by date
for (let i = 0; i < book_list.length; i ) {
createTd(book_list[i].date);
createTd(book_list[i].authName);
createTd(book_list[i].email);
createTd(book_list[i].title);
createTd(book_list[i].type);
createTd(book_list[i].price);
createTd(book_list[i].lang);
}
CodePudding user response:
I believe the problem is, as soon as you create a <td>
, you add it to a <tr>
but you also immediately append this <tr>
to your table. As a result, your table gets filled with <tr>
containing only one <td>
.
Also I rewrote your for
loop so as to avoid repeating yourself, and also make the book
keys dynamic, in case you want to add more later (rating, recap, etc. for instance)
let tr;
function createTd(content) {
let td = document.createElement('td');
td.appendChild(document.createTextNode(content));
tr.appendChild(td);
}
const keys = Object.keys(book_list[0]); // ["date","authName",...]
for (let book of books) {
tr = document.createElement('tr'); // Create a new row for each book
for(let key of keys) {
createTd(book[key]); // Append all the cells in the same row
}
table.appendChild(tr); // Add the row to the table
}