MediaWiki:AddressFromCepJqueryVersion.js
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/jquery/
$(document).ready(function () {
"use strict";
function cleanAddressFields() {
// It cleans values from address fields.
// "\\" is the scape way of jQuery
$("[name=User\\[street\\]]").val("");
$("[name=User\\[neighborhood\\]]").val("");
$("[name=User\\[Has\\ city\\]]").val("");
$("[name=User\\[state\\]]").val("");
}
// When CEP field ("postalCode") loses focus.
$("[name=User\\[postalCode\\]]").blur(function () {
// A new variable "cep" is made with only digits.
var cep = $(this).val().replace(/\D/g, "");
// Testing if the CEP variable has any value.
if (cep !== "") {
// Regular expression to validate CEP.
var 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.
$("[name=User\\[street\\]]").val("...");
$("[name=User\\[neighborhood\\]]").val("...");
$("[name=User\\[Has\\ city\\]]").val("...");
$("[name=User\\[state\\]]").val("...");
// It queries the web service viacep.com.br
$.getJSON("https://viacep.com.br/ws/" + cep + "/json/?callback=?", function (dados) {
if (!("erro" in dados)) {
// It updates the address fields with the data from the query.
$("[name=User\\[street\\]]").val(dados.logradouro);
$("[name=User\\[neighborhood\\]]").val(dados.bairro);
$("[name=User\\[Has\\ city\\]]").val(dados.localidade);
$("[name=User\\[state\\]]").val(dados.uf);
}
else {
// The CEP searched was not found.
cleanAddressFields();
alert("CEP não encontrado.");
}
});
}
else {
// The CEP is invalid.
cleanAddressFields();
alert("Formato de CEP inválido.");
}
}
else {
// The CEP is empty, it cleans the form fields.
cleanAddressFields();
}
});
});