Skip to content

Instantly share code, notes, and snippets.

@LucianoCharlesdeSouza
Created August 7, 2020 20:49
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save LucianoCharlesdeSouza/9a530dac1b050165921f25189f2c1334 to your computer and use it in GitHub Desktop.
Save LucianoCharlesdeSouza/9a530dac1b050165921f25189f2c1334 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Cidade por Estado</title>
</head>
<body>
<select name="estados" id="estados"></select>
<select name="cidades" id="cidades" disabled="disabled"></select>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
$(function () {
$.ajax({
url: 'https://servicodados.ibge.gov.br/api/v1/localidades/estados',
method: 'GET',
dataType: 'json',
success: function (response) {
let estados = response.sort(function (a, b) {
if (a.nome > b.nome) {
return 1;
}
if (a.nome < b.nome) {
return -1;
}
return 0;
});
let estadosHtml = '';
for (estado of estados) {
estadosHtml += `<option value="${estado.id}">${estado.nome}</option>`;
}
$('select[name="estados"]').html(estadosHtml);
}
});
$('select[name="estados"]').change(function () {
let id = $(this).val();
$.ajax({
url: `https://servicodados.ibge.gov.br/api/v1/localidades/estados/${id}/municipios`,
method: 'GET',
dataType: 'json',
beforeSend:function(response){
$('select[name="cidades"]').prop('disabled', true);
},
success: function (response) {
let cidades = response.sort(function (a, b) {
if (a.nome > b.nome) {
return 1;
}
if (a.nome < b.nome) {
return -1;
}
return 0;
});
let cidadesHtml = '';
for (cidade of cidades) {
cidadesHtml += `<option value="${cidade.id}">${cidade.nome}</option>`;
}
$('select[name="cidades"]').html(cidadesHtml);
$('select[name="cidades"]').prop('disabled', false);
}
});
});
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment