-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
49 lines (41 loc) · 1.35 KB
/
script.js
File metadata and controls
49 lines (41 loc) · 1.35 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
const warningMessage = document.querySelector(".warningMessage")
const fieldCep = document.querySelector("#cep")
const warning = (message, opacity) => {
warningMessage.style.opacity = `${opacity}`;
warningMessage.innerHTML = `${message}`
fieldCep.focus()
};
const fillForm = result => {
for (const campo in result) {
if (document.querySelector("#" + campo)) {
document.querySelector("#" + campo).value = result[campo]
}
}
}
const clearForm = () => {
const allField = document.querySelectorAll(".input-container > input")
for (let i = 1; i < allField.length; i++) {
allField[i].value = ""
}
}
const isNumber = number => /^[0-9]+$/.test(number)
const validCep = cep => cep.length == 8 && isNumber(cep)
const searchCep = async () => {
clearForm()
warning("none", 0)
const cep = fieldCep.value.replace("-", "")
const url = `https://viacep.com.br/ws/${cep}/json/`
if (cep == "") {
warning('Preencha o campo!', 1)
} else if (validCep(cep)) {
const data = await fetch(url)
const fullAddress = await data.json()
fullAddress.hasOwnProperty("erro") ? warning("Cep não encontrado!", 1) : fillForm(fullAddress)
}else{
warning("ERRO! Cep inválido.", 1)
}
}
document.getElementById("search").addEventListener("click", (e) => {
e.preventDefault()
searchCep()
})