</>
Consulta de CEP
/Exemplo JavaScript

Exemplo com JavaScript

Auto preenchimento de endereço via CEP usando JavaScript puro (Fetch API). Digite o CEP e ao sair do campo o endereço será preenchido.

Teste ao vivo

Código fonte completo

<!DOCTYPE html>
<html lang="pt-BR">
<head>
  <meta charset="UTF-8">
  <title>Consulta de CEP - JavaScript</title>
  <style>
    * { box-sizing: border-box; font-family: system-ui, sans-serif; }
    body { max-width: 500px; margin: 40px auto; padding: 0 20px; }
    label { display: block; margin-top: 12px; font-size: 14px; color: #555; }
    input { width: 100%; padding: 8px 12px; margin-top: 4px; border: 1px solid #ddd; border-radius: 6px; font-size: 14px; }
    input:focus { outline: none; border-color: #7c3aed; }
    h1 { font-size: 20px; }
  </style>
</head>
<body>

<h1>Auto Preenchimento de Endereço via CEP</h1>
<p>Digite o CEP e ao sair do campo o endereço será preenchido automaticamente.</p>

<form>
  <label>CEP:
    <input type="text" id="cep" maxlength="9" placeholder="00000-000">
  </label>
  <label>Rua:
    <input type="text" id="rua" readonly>
  </label>
  <label>Bairro:
    <input type="text" id="bairro" readonly>
  </label>
  <label>Cidade:
    <input type="text" id="cidade" readonly>
  </label>
  <label>Estado:
    <input type="text" id="uf" readonly>
  </label>
  <label>IBGE:
    <input type="text" id="ibge" readonly>
  </label>
</form>

<script>
  function limparFormulario() {
    document.getElementById("rua").value = "";
    document.getElementById("bairro").value = "";
    document.getElementById("cidade").value = "";
    document.getElementById("uf").value = "";
    document.getElementById("ibge").value = "";
  }

  document.getElementById("cep").addEventListener("blur", async function () {
    const cep = this.value.replace(/\D/g, "");

    if (cep.length !== 8) {
      limparFormulario();
      return;
    }

    // Preenche com "..." enquanto busca
    document.getElementById("rua").value = "...";
    document.getElementById("bairro").value = "...";
    document.getElementById("cidade").value = "...";
    document.getElementById("uf").value = "...";
    document.getElementById("ibge").value = "...";

    try {
      const response = await fetch(`/ws/${cep}/json/`);
      const dados = await response.json();

      if (dados.erro) {
        limparFormulario();
        alert("CEP não encontrado.");
        return;
      }

      document.getElementById("rua").value = dados.logradouro;
      document.getElementById("bairro").value = dados.bairro;
      document.getElementById("cidade").value = dados.localidade;
      document.getElementById("uf").value = dados.uf;
      document.getElementById("ibge").value = dados.ibge;
    } catch {
      limparFormulario();
      alert("Erro ao consultar o CEP.");
    }
  });
</script>

</body>
</html>