I am trying to create a table where each row will be an object in an array. Logically it works, but it gives me the number of rows in the table equal to the number of objects in the array each time I perform the function. Instead, I need the serial number of the row to be equal to the serial number of the object in the array. How can I achieve this? (* beginner's class project. can't use advanced js/libraries).
<html>
<head>
<style>
table,
th,
td,
tr {
border: 1px solid black;
}
</style>
</head>
<body>
<form>
<input id="firstname" type="text" placeholder="firstname"></input><br>
<input id="lastname" type="text" placeholder="lastname"></input><br>
</form>
<button onclick="myFunc()">calc</button>
<div></div>
</body>
<script>
let properties = [
'firstname',
'lastname',
]
let form = document.querySelector('form')
let div = document.querySelector('div')
let user = {}
let users = []
function myFunc() {
users.push(user)
for (let prop of properties) {
user[prop] = form.elements[prop].value
}
for (let user of users) {
//HERE is my problem. do i need to create separate function to calculate nubers and another one to render the table?
let tr = document.createElement('tr')
for (let key in user) {
let td = document.createElement('td')
td.innerHTML = user[key]
tr.appendChild(td)
}
let table = document.createElement('table')
table.appendChild(tr)
div.appendChild(table)
form.reset()
console.log(users.length)
}
}
</script>
</html>
CodePudding user response:
I'm not sure if I understood you correctly but I think you were pretty close. The thing is that, how it currently is, you never delete items from the object, you only add. So you don't have to render the whole table from the beginning therefore you don't need the for loop.
<html>
<head>
<style>
table,
th,
td,
tr {
border: 1px solid black;
}
</style>
</head>
<body>
<form>
<input
id="firstname"
type="text"
placeholder="firstname"></input><br>
<input
id="lastname"
type="text"
placeholder="lastname"></input><br>
</form>
<button
onclick="myFunc()">calc</button>
<div>
</div>
</body>
<script>
let properties = [
'firstname',
'lastname',
]
let form = document.querySelector('form')
let div = document.querySelector('div')
let user = {}
let users = []
function myFunc() {
users.push(user)
for (let prop of properties) {
user[prop] = form.elements[prop].value
}
let tr = document.createElement('tr')
for (let key in user) {
let td = document.createElement('td')
td.innerHTML = user[key]
tr.appendChild(td)
}
let table = document.querySelector("table")
if (table === null) {
table = document.createElement('table');
}
table.appendChild(tr)
div.appendChild(table)
form.reset()
console.log(users.length);
}
</script>
</html>