0
I have a form with two selects, one from State and another from City. I already get popular my city select according to the state choice. The problem is that at the time of return Json in the option, the date-latitude and date-longitude fields are repeated with the same values.
HTML
<form action="obrigado.php" method="post" class="form" id="location__form">
<fieldset class="row">
<div class="col-sm-6">
<select name="location__uf" id="location__uf" class="form-control required state">
<option value=""></option>
</select>
</div>
<div class="col-sm-6">
<select name="location__cidade" id="location__cidade" class="form-control required city">
<option value="">Cidade</option>
</select>
</div>
</fieldset>
</form>
Script
$.getJSON('js/estados-cidades.json', function (data) {
var items = [];
var options = '<option value="">Escolha um estado</option>';
$.each(data, function (key, val) {
options += '<option value="' + val.nome + '">' + val.nome + '</option>';
});
$("#location__uf").html(options);
$("#location__uf").change(function () {
var options_cidades = '';
var str = "";
$("#location__uf option:selected").each(function () {
str += $(this).text();
});
$.each(data, function (key, val) {
if (val.nome == str) {
$.each(val.latitudes, function (key_lat, val_lat) {
latitude = val_lat;
console.log(latitude);
});
$.each(val.longitudes, function (key_lat, val_long) {
longitude = val_long;
console.log(longitude);
});
$.each(val.cidades, function (key_city, val_city) {
options_cidades += '<option value="' + val_city + '" data-lat="' + latitude + '" data-long="' + longitude + '">' + val_city + '</option>';
});
}
});
$("#location__cidade").html(options_cidades);
}).change();
});
JSON
[
{
"sigla": "PI",
"nome": "Piauí",
"cidades": [
"Teresina",
"Parque Piauí",
"Água Branca"
],
"latitudes": [
"Teresina-lat",
"Parque Piauí-lat",
"Água Branca-lat"
],
"longitudes": [
"Teresina-long",
"Parque Piauí-long",
"Água Branca-long"
]
}
]