Created
May 7, 2024 23:30
-
-
Save dantetesta/346a2f22c5067f2095d51166160dea84 to your computer and use it in GitHub Desktop.
VIA CEP JetFormBuilder
This file contains 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
jQuery(document).ready(function($) { | |
var cepId = '#chckant_cep'; | |
var enderecoId = '#chckant_endereco'; | |
var bairroId = '#chckant_bairro'; | |
var cidadeId = '#chckant_cidade'; | |
var estadoId = '#chckant_estado'; | |
var numeroId = '#chckant_numero'; | |
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).trigger('change').trigger('blur'); | |
$(bairroId).val(dados.bairro).trigger('change').trigger('blur'); | |
$(cidadeId).val(dados.localidade).trigger('change').trigger('blur'); | |
$(estadoId).val(dados.uf).trigger('change').trigger('blur'); | |
setTimeout(function() { | |
$(enderecoId).trigger('change'); // Re-trigger change event after a delay | |
$(bairroId).trigger('change'); | |
$(cidadeId).trigger('change'); | |
$(estadoId).trigger('change'); | |
}, 100); // Delay in milliseconds | |
} | |
else { | |
alert("CEP não encontrado."); | |
} | |
}); | |
} | |
else { | |
alert("Formato de CEP inválido."); | |
} | |
} | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment