-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
80 lines (69 loc) · 2.43 KB
/
script.js
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
document.addEventListener('DOMContentLoaded', () => {
const form = document.getElementById('form');
const nameInput = document.getElementById('name');
const emailInput = document.getElementById('email');
const indexInput = document.getElementById('index');
const dataTable = document.getElementById('dataTable').getElementsByTagName('tbody')[0];
form.addEventListener('submit', (event) => {
event.preventDefault();
const name = nameInput.value;
const email = emailInput.value;
const index = indexInput.value;
if (index === '') {
createItem(name, email);
} else {
updateItem(index, name, email);
}
form.reset();
indexInput.value = '';
renderTable();
});
function createItem(name, email) {
const items = getItems();
items.push({ name, email });
saveItems(items);
}
function updateItem(index, name, email) {
const items = getItems();
items[index] = { name, email };
saveItems(items);
}
function deleteItem(index) {
const items = getItems();
items.splice(index, 1);
saveItems(items);
renderTable();
}
function editItem(index) {
const items = getItems();
const item = items[index];
nameInput.value = item.name;
emailInput.value = item.email;
indexInput.value = index;
}
function getItems() {
return JSON.parse(localStorage.getItem('items')) || [];
}
function saveItems(items) {
localStorage.setItem('items', JSON.stringify(items));
}
function renderTable() {
const items = getItems();
dataTable.innerHTML = '';
items.forEach((item, index) => {
const row = dataTable.insertRow();
row.insertCell(0).textContent = item.name;
row.insertCell(1).textContent = item.email;
const actionsCell = row.insertCell(2);
const editButton = document.createElement('button');
editButton.textContent = 'Editar';
editButton.onclick = () => editItem(index);
actionsCell.appendChild(editButton);
const deleteButton = document.createElement('button');
deleteButton.textContent = 'Deletar';
deleteButton.onclick = () => deleteItem(index);
actionsCell.appendChild(deleteButton);
});
}
renderTable();
});