Last active
August 4, 2025 19:52
-
-
Save dantetesta/da761423a9d67f4566dc99b000b186ba to your computer and use it in GitHub Desktop.
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
| <script> | |
| /* | |
| AUTOR: DANTE TESTA | |
| FUNÇÃO: PESQUISA CEP NA API VIA CEP + CONCATENAÇÃO DE ENDEREÇO | |
| DATA: 18/05/2023 | |
| */ | |
| jQuery(document).ready(function($) { | |
| /*SETUP DE CAMPOS DO FORMULÁRIO - Altere com seus seletores abaixo! */ | |
| var cepId = '#cep'; | |
| var enderecoId = '#endereco'; | |
| var bairroId = '#bairro'; | |
| var cidadeId = '#cidade'; | |
| var estadoId = '#estado'; | |
| var numeroId = '#numero'; | |
| var enderecoCompletoId = '#endereco-completo'; | |
| /* ----------------- NÃO MECHA ABAIXO -------------*/ | |
| function setLoading(loading) { | |
| var loadingText = 'Carregando...'; | |
| if (loading) { | |
| $(enderecoId).val(loadingText); | |
| $(bairroId).val(loadingText); | |
| $(cidadeId).val(loadingText); | |
| $(estadoId).val(loadingText); | |
| } else { | |
| $(enderecoId).val(''); | |
| $(bairroId).val(''); | |
| $(cidadeId).val(''); | |
| $(estadoId).val(''); | |
| } | |
| } | |
| $(cepId).change(function() { | |
| let cep = $(this).val().replace(/\D/g, ''); | |
| if (cep != "") { | |
| let validacep = /^[0-9]{8}$/; | |
| if(validacep.test(cep)) { | |
| setLoading(true); | |
| $.getJSON("https://viacep.com.br/ws/"+ cep +"/json/?callback=?", function(dados) { | |
| setLoading(false); | |
| if (!("erro" in dados)) { | |
| // Atualiza os campos com os valores da consulta. | |
| $(enderecoId).val(dados.logradouro); | |
| $(bairroId).val(dados.bairro); | |
| $(cidadeId).val(dados.localidade); | |
| $(estadoId).val(dados.uf); | |
| updateEnderecoCompleto(); | |
| } | |
| else { | |
| alert("CEP não encontrado."); | |
| } | |
| }); | |
| } | |
| else { | |
| alert("Formato de CEP inválido."); | |
| } | |
| } | |
| }); | |
| $(numeroId).on('input', function() { | |
| updateEnderecoCompleto(); | |
| }); | |
| function updateEnderecoCompleto() { | |
| let enderecoCompleto = $(enderecoId).val() + ', ' + | |
| $(numeroId).val() + ', ' + | |
| $(cidadeId).val() + ', ' + | |
| $(estadoId).val(); | |
| $(enderecoCompletoId).val(enderecoCompleto); | |
| } | |
| }); | |
| </script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment