-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
103 lines (75 loc) · 2.92 KB
/
index.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
const nomeInput = document.querySelector("#name");
const dataInput = document.querySelector("#birth-date");
const botao = document.querySelector("#botao");
const tabela = document.querySelector(".js-tabela");
const pessoas = JSON.parse(localStorage.getItem('pessoas')) || [];
exibirDados();
botao.addEventListener("click", (e)=>{
e.preventDefault();
if(!nomeInput.validity.valid){
alert('nome invalido');
}if(!dataInput.validity.valid){
alert('Data invalida');
}if(nomeInput.validity.valid && dataInput.validity.valid){
// SALVANDO PESSOAS(OBJETO) NO LOCALSTORAGE
pessoas.push({nome: nomeInput.value, nascimento: dataInput.value});
localStorage.setItem('pessoas', JSON.stringify(pessoas));
resetarPagina();
}
})
tabela.addEventListener("click", (e)=>{
e.preventDefault();
if(e.target.parentNode.id){
const idNumber = parseInt(e.target.parentNode.id);
//ALTERAR DADOS
if(e.target.attributes.class.nodeValue == "pessoa-editar"){
if(nomeInput.value == "" || dataInput.value == ""){
alert("Insira os dados que deseja alterar");
nomeInput.focus();
}else {
if(!nomeInput.validity.valid){
alert('nome invalido');
}if(!dataInput.validity.valid){
alert('Data invalida');
}else {
pessoas.splice(idNumber, 1, {nome: nomeInput.value, nascimento: dataInput.value});
localStorage.setItem('pessoas', JSON.stringify(pessoas));
resetarPagina();
}
}
}
// EXCLUIR DADOS
if(e.target.attributes.class.nodeValue == "pessoa-excluir"){
alert(`Dados do: ${ pessoas[idNumber].nome} foram excluidos`);
pessoas.splice(idNumber,1);
localStorage.setItem('pessoas', JSON.stringify(pessoas));
resetarPagina();
}
}
})
//FORMATANDO A DATA DE YYYY-MM-DD para DD/MM/YYYY
function getFormattedDate(dateString) {
const date = new Date(dateString)
var year = date.getFullYear();
var month = (1 + date.getMonth()).toString();
month = month.length > 1 ? month : '0' + month;
var day = (1 + date.getDate()).toString();
day = day.length > 1 ? day : '0' + day;
return day + '/' + month + '/' + year;
}
function resetarPagina(){
nomeInput.value = "";
dataInput.value = "";
window.location.reload();
}
function exibirDados(){
for(var i = 0; i < pessoas.length; i++) {
tabela.insertAdjacentHTML("beforeend",`
<tr>
<td>${pessoas[i].nome}</td>
<td>${getFormattedDate(pessoas[i].nascimento)}</td>
<td id=${i} ><a class="pessoa-editar" href="#">editar</a> <a class="pessoa-excluir" href="#">excluir</a></td>
</tr>
`);
}
}