-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
71 lines (65 loc) · 2.72 KB
/
script.js
File metadata and controls
71 lines (65 loc) · 2.72 KB
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
document.addEventListener('DOMContentLoaded', () => {
const employeeForm = document.getElementById("employeeForm");
const employeeTable = document
.getElementById("employeeTable")
.getElementsByTagName("tbody")[0];
const apiBaseUrl = "http://localhost:8081/api/employees";
function fetchEmployees() {
fetch(apiBaseUrl)
.then((response) => response.json())
.then((data) => {
employeeTable.innerHTML = "";
data.forEach((employee) => {
const row = employeeTable.insertRow();
row.innerHTML =
`<td>${employee.id}</td>
<td>${employee.firstName}</td>
<td>${employee.lastName}</td>
<td>${employee.email}</td>
<td>
<button
onclick="editEmployee(${employee.id})">Edit</button>
<button
onclick="deleteEmployee (${employee.id})">Delete</button>
</td>`;
});
});
}
employeeForm.addEventListener("submit", (e) => {
e.preventDefault();
const id = document.getElementById("employeeId").value;
const firstName = document.getElementById("firstName").value;
const lastName = document.getElementById("lastName").value;
const email = document.getElementById("email").value;
const method = id ? "PUT" : "POST";
const url = id ? `${apiBaseUrl}/${id}` : apiBaseUrl;
fetch(url, {
method: method,
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ firstName, lastName, email }),
})
.then((response) => response.json())
.then(() => {
employeeForm.reset();
fetchEmployees();
});
});
window.editEmployee = function (id) {
fetch(`${apiBaseUrl}/${id}`)
.then((response) => response.json())
.then((employee) => {
document.getElementById("employeeId").value = employee.id;
document.getElementById("firstName").value = employee.firstName;
document.getElementById("lastName").value = employee.lastName;
document.getElementById("email").value = employee.email;
});
};
window.deleteEmployee = function (id) {
fetch(`${apiBaseUrl}/${id}`, {
method: "DELETE",
}).then(() => fetchEmployees());
};
fetchEmployees();
});