I’m trying to get the field ‘sigla’ from a JSON file and put it on a HTML ‘option object’, but it’s refusing to work as it should.. hope some of you out there can help me with that!
This is a sample of the JSON file:
{
"estados": [
{
"sigla": "AC",
"nome": "Acre",
"cidades": [
"Acrelândia",
"Assis Brasil"
]
},
{
"sigla": "AL",
"nome": "Alagoas",
"cidades": [
"Água Branca",
"Anadia"
]
}, ...
]
}
Script:
<script>
$.getJSON("json/estados.json", function (data){
$.each(data.estados, function (keyEstados, valEstados){
var output = '';
output += '<option value="" disabled="disabled" selected>UF</option>';
$.each(valEstados.sigla, function (keySigla, valSigla){
output += '<option value="' + valSigla + '">' + valSigla + '</option>';
});
$('#selection').html(output);
});
});
</script>
Where it should fit in:
<div class="col-sm-6">
<div class="inputBox">
<div class="inputText">Selecione seu estado*
<select id="selection" name="estado_php" required>
<option value="" disabled="disabled" selected>UF</option>
</select>
</div>
</div>
</div>
2
Answers
Have you tried using the “developer” mode in your browser to set breakpoints in your code to debug it? E.g. on Firefox, the menu has a top level entry to “Web Developer”->”Debugger”.
If you do, I think you will find have mixed up your loops. The first loop looks OK in that
should match the list starting
However, I don’t think the second loop starting
is needed. I think your code needs to look more like this:
(not tested, but it basically gets rid of the inner loop).
It seems to me that you are fetching the
valEstados.sigla
as it was an object or an array ($.each(valEstados.sigla)
and it has the value you need to set theoptions
.Besides that, you are setting a disabled option and the html of the select one time for each
data.estados
instead of just once.This should work: