2019-2020/Formations/NSI/Bloc1/WEB/SuperTable/script.js

104 lines
2.9 KiB
JavaScript
Raw Normal View History

2020-05-05 07:53:14 +00:00
/* 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(`<tr>
<th>${d.firstname}</th>
<th>${d.lastname}</th>
<th>${d.age}</th>
<th><button class="modifier">Mod</button><button class="remover">Del</button></th>
</tr>`)
}, "")
}
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 += `<tr>
<th><input id="firstname"></input></th>
<th><input id="lastname"></input></th>
<th><input id="age"></input></th>
<th><button id="save">Ok</button><button id="cancel">Ann</button></th>
</tr>`
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 = `<button id="save">Ok</button><button id="cancel">Ann</button>`
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 = `<input id="firstname" value=${firstname} ></input></th>`
cells[1].innerHTML = `<input id="lastname" value=${lastname} ></input></th>`
cells[2].innerHTML = `<input id="age" value=${age} ></input></th>`
}
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()
}