Created
December 17, 2020 16:40
-
-
Save luisvinicius09/6df8517df6a2e01ced166d118f0de289 to your computer and use it in GitHub Desktop.
Address autocomplete for Brazil
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This is a code for autocomplete the address in forms using ViaCEP endpoint. | |
<script> | |
function clean_forms() { | |
document.getElementById('street').value = (''); | |
document.getElementById('district').value = (''); | |
document.getElementById('city').value = (''); | |
document.getElementById('uf').value = (''); | |
} | |
function my_cb(content) { | |
if (!("erro" in content)) { | |
document.getElementById('street').value = (content.logradouro); | |
document.getElementById('district').value = (content.bairro); | |
document.getElementById('city').value = (content.localidade); | |
document.getElementById('uf').value = (content.uf); | |
} else { | |
clean_forms(); | |
alert('CEP não encontrado'); | |
} | |
} | |
function searchCep(value) { | |
let cep = value.replace(/\D/g, ''); | |
if (cep != '') { | |
var validationCep = /^[0-9]{8}$/; | |
if (validationCep.test(cep)) { | |
document.getElementById('street').value = '...'; | |
document.getElementById('district').value = '...'; | |
document.getElementById('city').value = '...'; | |
document.getElementById('uf').value = '...'; | |
let script = document.createElement('script'); | |
script.src = 'https://viacep.com.br/ws/' + cep + '/json/?callback=my_cb'; | |
document.body.appendChild(script); | |
} else { | |
clean_forms(); | |
alert('Formato de CEP inválido.'); | |
} | |
} else { | |
clean_forms(); | |
} | |
} | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment