MediaWiki:AddressFromCep.js

De Wikincat
Revisão de 16h38min de 11 de julho de 2020 por imp>Jaider (version without jQuery)
(dif) ← Edição anterior | Revisão atual (dif) | Versão posterior → (dif)
Ir para navegação Ir para pesquisar

Nota: Após publicar, você pode ter que limpar o "cache" do seu navegador para ver as alterações.

  • Firefox / Safari: Pressione Shift enquanto clica Recarregar, ou pressione Ctrl-F5 ou Ctrl-R (⌘-R no Mac)
  • Google Chrome: Pressione Ctrl-Shift-R (⌘-Shift-R no Mac)
  • Internet Explorer/Edge: PressioneCtrl enquanto clica Recarregar, ou Pressione Ctrl-F5
  • Opera: Pressione Ctrl-F5.
// Adapted from https://viacep.com.br/exemplo/javascript/
function cleanAddressesFields() {
    // It cleans values from addresses fields.
    document.getElementById("input_6").value = ("");
    document.getElementById("input_7").value = ("");
    document.getElementById("input_8").value = ("");
    document.getElementById("input_9").value = ("");
}
function myCallback(dados) {
    if (!("erro" in dados)) {
        // It updates the addresses fields with the data from the query.
        document.getElementById("input_6").value = (dados.logradouro);
        document.getElementById("input_7").value = (dados.bairro);
        document.getElementById("input_8").value = (dados.localidade);
        document.getElementById("input_9").value = (dados.uf);
    }
    else {
        // The CEP searched was not found.
        cleanAddressesFields();
        alert("CEP não encontrado.");
    }
}
function searchCep(value) {
    // A new variable "cep" is made with only digits.
    let cep = value.replace(/\D/g, "");
    // Testing if the CEP variable has any value.
    if (cep !== "") {
        // Regular expression to validate CEP.
        let cepValidator = /^[0-9]{8}$/;
        // Testing CEP validation. If true...
        if (cepValidator.test(cep)) {
            // It fills the address fields with "..." while the web service is busy.
            document.getElementById("input_6").value = "...";
            document.getElementById("input_7").value = "...";
            document.getElementById("input_8").value = "...";
            document.getElementById("input_9").value = "...";
            // It creates a javaScript element.
            let script = document.createElement("script");
            // It sincronizes with callback.
            script.src = "https://viacep.com.br/ws/" + cep + "/json/?callback=myCallback";
            // It inserts the script into the document and load the contents.
            document.body.appendChild(script);
        }
        else {
            // The CEP is invalid.
            cleanAddressesFields();
            alert("Formato de CEP inválido.");
        }
    }
    else {
        // The CEP is empty, it cleans the form fields.
        cleanAddressesFields();
    }
}
document.getElementById("input_4").setAttribute("onblur", "searchCep(this.value)");