-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
31 lines (24 loc) · 920 Bytes
/
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
var cep = document.getElementById('cep');
var cidade = document.getElementById('cidade');
var logradouro = document.getElementById('logradouro');
var estado = document.getElementById('estado');
var erro = document.getElementById('erro');
cep.addEventListener("focusout", () => buscaEndereco(cep.value));
async function buscaEndereco(cep) {
erro.innerHTML = "";
try{
var consultaCEP = await fetch(`https://viacep.com.br/ws/${cep}/json/`);
var CEPConvertido = await consultaCEP.json();
if (CEPConvertido.erro){
throw Error('CEP inexistente!');
}
cidade.value = CEPConvertido.localidade;
logradouro.value = CEPConvertido.logradouro;
estado.value = CEPConvertido.uf;
console.log(CEPConvertido);
return CEPConvertido;
}
catch(erro){
erro.innerHTML = '<p> CEP inválido. Tente Novamente! </p>';
}
}