I'm trying make table generator for HTML with JavaScript. When I tried generate, the first field is created successfully. But auto-filling doesn't work correctly.
How can I solve this problem?
My Library code:
export default class Table {
#maxlength
constructor(body) {
this.body = body
this.parent = document.createElement('table')
this.body.append(this.parent)
this.#maxlength = 0;
}
add(...values) {
let element = document.createElement('tr')
let elname = this.parent.childElementCount < 1 ? "th" : "td"
function add(value) {
let addval = document.createElement(elname)
addval.textContent = value
element.append(addval)
}
[...values].map(el => {
add(el)
})
if(this.#maxlength - [...values].length > 0) {
new Array(this.#maxlength - [...values].length).map(el => {
add("")
})
}
if (this.#maxlength < [...values].length) {
this.#maxlength = [...values].length
}
this.parent.append(element)
}
}
My HTML Javascript:
import Table from './Table.js'
const { body } = document;
let table = new Table(body)
table.add("a","a","a")
table.add("a","a","a")
table.add("a","a","a")
table.add("a","a") // AUTOFILLING
table.add("a") // AUTOFILLING
table.add("a","a") // AUTOFILLING
table.add("a","a","a")
It appears you were creating the th or td elements but they were never added to the tr element. I believe this was primarily due to the fact that you weren't actually appending the empty entries into values as intended. Comparing values.length to this.#maxlength in a while loop resolves this issue as seen in the code snippet below:
class Table {
#maxlength;
constructor(body) {
this.body = body;
this.parent = document.createElement('table');
this.body.append(this.parent);
this.#maxlength = 0;
}
add(...values) {
let element = document.createElement('tr');
let elname = this.parent.childElementCount < 1 ? "th" : "td";
// Add blank entries for null values
while (values.length < this.#maxlength) {
values.push("");
}
function add(value) {
let addval = document.createElement(elname);
addval.textContent = value;
element.append(addval);
}
[...values].forEach(el => {
add(el);
});
if (this.#maxlength - [...values].length > 0) {
new Array(this.#maxlength - [...values].length).forEach(el => {
add("");
});
}
if (this.#maxlength < [...values].length) {
this.#maxlength = [...values].length;
}
this.parent.append(element);
}
}
const {
body
} = document;
let table = new Table(body);
table.add("a", "a", "a");
table.add("a", "a", "a");
table.add("a", "a", "a");
table.add("a", "a"); // AUTOFILLING
table.add("a"); // AUTOFILLING
table.add("a", "a"); // AUTOFILLING
table.add("a", "a", "a");
table,
th,
td {
border: 1px solid black;
}
th,
td {
width: 1.5rem;
}