-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
361 lines (316 loc) · 14.8 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8">
<title>CRUD-Anwendung Mitarbeiter</title>
<!--
Ziel ist eine CRUD-Anwendung, in der Mitarbeiter
- erstellt
- angezeigt
- geändert und
- gelöscht werden können
Aufgabe 1: erstelle ein javascript, dass bei Knopfdruck auf "Hinzufügen":
- überprüft, dass beide input-Felder nicht leer sind
- eine neue id erstellt (es soll fortlaufend hochgezählt werden)
- die id, den Vornamen, den Nachnamen und den Monatslohn in der Tabelle ergänzt
- die input-Felder für die nächste Eingabe leert
- dabei soll ein Array aus Mitarbeiter-Objekten erstellt werden,
- welches alle aktuellen Mitarbeiter enthält
-->
<style>
.headers {
font-weight: bold;
}
</style>
</head>
<body onload="drawTable()">
<h2>Mitarbeiter</h2>
<div>
<label for="firstNameInput">Vorname: </label><input type="text" id="firstNameInput">
<label for="lastNameInput">Nachname: </label><input type="text" id="lastNameInput">
<label for="monSalInput">Monatslohn: </label><input type="text" id="monSalInput">
<button type="button" id="addButton">Hinzufügen</button>
</div>
<br>
<div id="ausgabe"></div>
<script>
class Employee {
static employeeNextId = Number(localStorage.getItem("nextId"));
// static employeeNextId = 1;
// constructor "overload".
constructor(first, last, salary, id = null) {
if (id == undefined) {
id = Employee.employeeNextId;
Employee.employeeNextId++;
}
this.id = id;
this.setFirstName(first);
this.setLastName(last);
this.setMonSal(salary);
}
// test(json) {
// Object.assign(this, json);
// }
// getter funktionen
// getFirstName() {
// return this.firstName;
// }
//
// getLastName() {
// return this.lastName;
// }
//
// getMonSal() {
// return this.monSal;
// }
// setter funktionen
setFirstName(newFirstName) {
if (newFirstName !== ""){
this.firstName = newFirstName.trim();
}
}
setLastName(newLastName) {
if (newLastName !== ""){
this.lastName = newLastName.trim();
}
}
setMonSal(newMonSal) {
if (newMonSal !== ""){
this.monSal = Number(newMonSal);
}
}
}
// class method zum pushen eines neu erstellten Employee objekts
Employee.add = function (obj) {
employeeArray.push(obj);
}
// array erstellen für alle Employee-objekte
let employeeArray = [];
// wenn werte für die keys "employeeJSONArray" und "nextId" in der localstorage existieren
if (localStorage.getItem("employeeJSONArray") && localStorage.getItem("nextId")) {
// dann hole die werte aus der localstorage
retrieveArray();
}
else {
// ansonsten füge die beispieldaten wieder hinzu und speichere sie ab
Employee.add(new Employee("Petra", "Pan", 2100));
Employee.add(new Employee("Freya", "Ridings", 2450.30));
storeArray("employeeJSONArray", employeeArray);
}
// diese funktion speichert das array und die nextId in der localstorage ab
function storeArray(name, arr) {
localStorage.setItem(name, JSON.stringify(arr));
console.log(localStorage);
localStorage.setItem("nextId", Employee.employeeNextId.toString());
}
// diese funktion liest das array aus der localstorage
function retrieveArray() {
let parsed = JSON.parse(localStorage.getItem("employeeJSONArray"));
employeeArray = reconstructObjects(parsed);
}
// diese funktion rekonstruiert die objekte aus der localstorage. mit json importierte objekte haben nicht die methoden
// der klasse, weil sie nicht beim aktuellen seitenaufruf durch den konstruktor erzeugt worden sind
function reconstructObjects(json) {
// ich erzeuge ein temporäres array
let arr = [];
// loope durch das array, das mit json importiert wurde
for (let i = 0; i < json.length; i++) {
// erzeugung neuer Employee objekte mit parametern aus dem jeweiligen "json-objekt"
const newEmp = new Employee(json[i].firstName, json[i].lastName, json[i].monSal, json[i].id);
arr.push(newEmp)
}
// funktion gibt das temporäre array zurück
return arr;
}
// funktion, die überprüft, ob ein übergebenes feld leer ist
function isNotEmpty(field) {
if (field.toString().trim() === "") {
return false;
}
else {
return true;
}
}
// funktion zum erzeugen von Employee objekten
function createEmployee() {
let first = document.getElementById("firstNameInput").value.trim();
let last = document.getElementById("lastNameInput").value.trim();
let monSal = document.getElementById("monSalInput").value.trim();
// unsere 3 felder werden auf leerheit überprüft
if (isNotEmpty(first) && isNotEmpty(last) && isNotEmpty(monSal)) {
// wenn sie nicht leer sind, wird ein neues Employee objekt erstellt
const newEmp = new Employee(first, last, Number(monSal));
// und mit der add methode ins array gepusht
Employee.add(newEmp);
// array wird in localstorage gespeichert
storeArray("employeeJSONArray", employeeArray);
// seite wird neu geladen
location.reload();
}
else {
// ansonsten gibts nen fehler
alert("Alle Felder müssen ausgefüllt sein.");
}
}
// initiale eventlistener für den addBtn mit createEmployee und addRow funktionen
document.getElementById("addButton").addEventListener("click", createEmployee);
document.getElementById("addButton").addEventListener("click", addRow);
// gleiche funktion wie addEmpListener, nur umgekehrt. ersetzt also create funktionalität durch die update funktionalität
function addUpdListener(id) {
let oldBtn = document.getElementById("addButton");
// hier wird ein klon des addbuttons erstellt. klone von objekten erhalten alle attribute des originals und ihre werte
// sowie die inline listener (onclick), nicht aber nachträglich hinzugefügte eventlistener
// damit erzeuge ich also den gleichen button, bloß ohne listener
let newBtn = oldBtn.cloneNode(true);
// hier ersetze ich den alten button im document durch den klon
oldBtn.parentNode.replaceChild(newBtn, oldBtn);
// und jetzt kommen andere event listener auf den button
document.getElementById("addButton").addEventListener("click", function () {
updateEmployee(employeeArray, id)
});
}
// überschriften für die tabelle
let headers = ["ID", "Vorname", "Nachname", "Monatslohn"];
// funktion zum erzeugen der tabelle
function drawTable() {
let tabelle = document.createElement("table");
document.getElementById("ausgabe").appendChild(tabelle);
let head = document.createElement("thead");
let body = document.createElement("tbody");
tabelle.appendChild(head);
tabelle.appendChild(body);
head.appendChild(document.createElement("tr"));
// hier wird die header row ausgefüllt
for (let i = 0; i < headers.length; i++) {
let td = document.createElement("td");
td.className = "headers";
let node = document.createTextNode(headers[i]);
td.appendChild(node);
document.getElementsByTagName("tr")[0].appendChild(td);
}
// Befüllen des table bodys mit den property values aller Mitarbeiter-objekte
for (let i = 0; i < employeeArray.length; i++) { // Für jeden Teilnehmer
let row = document.createElement("tr"); // erzeuge eine tr
for (const attribut in employeeArray[i]) { // für jedes attribut im objekt
let td = document.createElement("td"); // erzeuge eine td
let node = document.createTextNode(employeeArray[i][attribut]); // erzeuge eine textnode mit dem attribut value
td.appendChild(node); // hänge node an td
row.appendChild(td); // hänge td an die tr
}
// die delete und update buttons bekommen bei erstellung die .id property es aktuellen objekts als id übergeben
createDeleteButton(row, employeeArray[i]["id"]);
createUpdateButton(row, employeeArray[i]["id"]);
document.getElementsByTagName("tbody")[0].appendChild(row); // hänge tr an den table body
}
}
// td mit button wird erstellt, button kriegt event listener und die id seines zugehörigen objekts
function createDeleteButton(row, id) {
let td = document.createElement("td");
let deleteButton = document.createElement("button");
deleteButton.setAttribute("type", "button");
deleteButton.className = "delButtons";
// deleteButtons bekommen die .id property ihres zugehörigen objekts als id zugeteilt
deleteButton.setAttribute("id", id);
deleteButton.innerHTML = "Löschen";
deleteButton.addEventListener("click", function () {
deleteEmployee(employeeArray, this.id)});
td.appendChild(deleteButton);
row.appendChild(td);
}
// loopt durch das array und wenn die property id eines objekts === die übergebene id vom button, dann löscht es diesen
// eintrag aus dem array, löscht den inhalt des ausgabe-divs und schreibt die tabelle neu rein
function deleteEmployee(array, index) {
// loop durch das array
for (let i = 0; i < array.length; i++) {
// wenn die .id property des aktuellen objekts mit der übergebenen id des buttons übereinstimmt
if (array[i].id.toString() === index) {
// splice das array an diesem index, also entferne dieses objekt aus dem array
array.splice(i, 1);
}
}
storeArray("employeeJSONArray", employeeArray);
location.reload();
}
// erstellung des updatebuttons
function createUpdateButton(row, id) {
let td = document.createElement("td");
let updateButton = document.createElement("button");
updateButton.setAttribute("type", "button");
updateButton.className = "updButtons";
// updateButtons bekommen die id "upd" + die .id ihrer zeile, damit sie sich von der id des delButtons unterscheidet
updateButton.setAttribute("id", "upd"+id);
updateButton.innerHTML = "Ändern";
// eventlistener zum aufruf der displayUpdateUI funktion. aufgerufen mit einem slice ab index 3, um aus upd1 eine 1 zu machen
updateButton.addEventListener("click", function () {
displayUpdateUI(employeeArray, this.id.slice(3))});
td.appendChild(updateButton);
row.appendChild(td);
}
// änderung des UIs von create auf update nach klick auf den updateButton
function displayUpdateUI(array, index) {
for (let i = 0; i < array.length; i++) {
if (array[i].id == index) {
// die zugehörigen mitarbeiterdaten werden in den input-feldern angezeigt
console.log(array[i].firstName);
document.getElementById("firstNameInput").value = array[i].firstName;
document.getElementById("lastNameInput").value = array[i].lastName;
document.getElementById("monSalInput").value = array[i].monSal;
// aufschrift des addBtn wird geändert auf "Ändern"
document.getElementById("addButton").innerHTML = "Ändern";
// eventlistener werden geändert
addUpdListener(index);
// updateButton wird ausgeblendet
document.getElementById("upd"+index).style.display = "none";
}
}
}
// funktion zum ändern des objekts im array
function updateEmployee(array, index) {
// loop durchs array
for (let i = 0; i < array.length; i++) {
// wenn die beim aufruf übergebene id mit der .id property des aktuellen objekts übereinstimmt...
if (array[i].id.toString() === index) {
// nehme die aktuellen values in den input-feldern und überschreibe damit die property values des objekts
// hierzu verwende ich die jeweiligen setter funktionen
array[i].setFirstName(document.getElementById("firstNameInput").value);
array[i].setLastName(document.getElementById("lastNameInput").value);
array[i].setMonSal(document.getElementById("monSalInput").value);
}
}
storeArray("employeeJSONArray", employeeArray);
// danach werden die input-felder geleert
resetInput(document.getElementById("firstNameInput"));
resetInput(document.getElementById("lastNameInput"));
resetInput(document.getElementById("monSalInput"));
location.reload();
}
// funktion zum hinzufügen einer reihe
function addRow() {
let first = document.getElementById("firstNameInput").value;
let last = document.getElementById("lastNameInput").value;
let monSal = document.getElementById("monSalInput").value;
if (isNotEmpty(first) && isNotEmpty(last) && isNotEmpty(monSal)) {
let row = document.createElement("tr");
// alle property values des letzten objekts im array werden in tds appended
for (const attribut in employeeArray[employeeArray.length - 1]) {
let td = document.createElement("td");
let node = document.createTextNode(employeeArray[employeeArray.length - 1][attribut]);
td.appendChild(node);
row.appendChild(td);
}
createDeleteButton(row, employeeArray[employeeArray.length - 1]["id"]);
createUpdateButton(row, employeeArray[employeeArray.length - 1]["id"]);
document.getElementsByTagName("tbody")[0].appendChild(row);
// alles fertig, jetzt werden die input felder gelöscht
resetInput(document.getElementById("firstNameInput"));
resetInput(document.getElementById("lastNameInput"));
resetInput(document.getElementById("monSalInput"));
}
}
// löschen der input felder
function resetInput(field) {
field.value = "";
}
</script>
</body>
</html>