/* eslint-disable no-unused-vars */
'use strict';
let datas = [
{
firstname: "Jill",
lastname: "Smith",
age: 50
},
{
firstname: "Eve",
lastname: "Jackson",
age: 94
},
]
let editing = false;
document.addEventListener('DOMContentLoaded', () => {
updateTable(datas);
//console.log(Array.from(document.getElementsByClassName('modifier')));
document.getElementById('addRow').onclick = () => appendQueryLine();
}, false);
function toggleEditing() {
editing = !editing
}
function feedDatas (datas) {
return datas.reduce( (acc, d) => {
return acc.concat(`
${d.firstname} |
${d.lastname} |
${d.age} |
|
`)
}, "")
}
function updateTable () {
let tbody = document.getElementById("datatable");
tbody.innerHTML = feedDatas(datas)
Array.from(document.getElementsByClassName('modifier')).map(d => d.onclick = () => modifyPersonne(d));
}
function appendQueryLine () {
if (!editing) {
editing = true
let tbody = document.getElementById("datatable");
tbody.innerHTML += `
|
|
|
|
`
document.getElementById('save').onclick= () => savePersonne();
document.getElementById('cancel').onclick= () => removeQueryLine();
} else {
console.log("Already editing")
}
}
function removeQueryLine () {
if (editing) {
feedDatas(datas)
updateTable()
toggleEditing()
}
}
function modifyPersonne (d) {
toggleEditing()
let cells = d.parentElement.parentElement.children
d.parentElement.innerHTML = ``
document.getElementById('save').onclick= () => savePersonne();
document.getElementById('cancel').onclick= () => removeQueryLine();
let firstname = cells[0].firstChild.nodeValue
let lastname = cells[1].firstChild.nodeValue
let age = cells[2].firstChild.nodeValue
cells[0].innerHTML = ``
cells[1].innerHTML = ``
cells[2].innerHTML = ``
}
function savePersonne () {
let firstname = document.getElementById("firstname");
let lastname = document.getElementById("lastname");
let age = document.getElementById("age");
datas.push(
{
firstname: firstname.value,
lastname: lastname.value,
age: age.value
}
)
updateTable()
toggleEditing()
}