Chained Select: how to use to select Brazilian municipalities in a JSON file from select states

4

EDITION

In the future, someone needs the jQuery version. Here is the code:

//select encadeado com JSON
$('#uf').on('change', function () {
    var estado = $(this).val(), cidade = $('#municipio');
    $.getJSON('json/municipios.json', function (resultado) {
        $.each(resultado, function (estadoProp, valor) {
            cidade.find('option').remove();
            if (estadoProp === estado) {
                for (var i in valor) {
                    var cidadeVal = valor[i];
                    cidade.append($("<option></option>").attr("value", cidadeVal).text(cidadeVal));
                }
                /* Esta parte aqui é por conta do plugin Bootstrap Select que eu estou usando. Obviamente, não é necessária se você não usa o plugin */
                cidade.selectpicker('refresh');
            }
        });
    });
});

I have a question about using the Chained Select plugin.

I have a combo box HTML with the Brazilian states, like this:

<select id="estado">
    <option value="">Selecione</option>
    <option value="AC">Acre</option>
    <option value="AL">Alagoas</option>
    <option value="AP">Amapá</option>
    <option value="AM">Amazonas</option>
    <option value="BA">Bahia</option>
    <option value="CE">Ceará</option>
    <option value="DF">Distrito Federal</option>
    <option value="ES">Espirito Santo</option>
    <option value="GO">Goiás</option>
    <option value="MA">Maranhão</option>
    <option value="MS">Mato Grosso do Sul</option>
    <option value="MT">Mato Grosso</option>
    <option value="MG">Minas Gerais</option>
    <option value="PA">Pará</option>
    <option value="PB">Paraíba</option>
    <option value="PR">Paraná</option>
    <option value="PE">Pernambuco</option>
    <option value="PI">Piauí</option>
    <option value="RJ">Rio de Janeiro</option>
    <option value="RN">Rio Grande do Norte</option>
    <option value="RS">Rio Grande do Sul</option>
    <option value="RO">Rondônia</option>
    <option value="RR">Roraima</option>
    <option value="SC">Santa Catarina</option>
    <option value="SP">São Paulo</option>
    <option value="SE">Sergipe</option>
    <option value="TO">Tocantins</option>
</select>

I would like to select the state and immediately have the municipalities of that state listed in another combo box from a JSON file.

The plugin is called as follows and is working, but does not bring the data correctly, as can be seen in the JSFiddle .

$("#municipio").remoteChained({
    parents : "#estado",
    url : "https://gist.githubusercontent.com/eduardo-almeida-II/6e1caf8875949b38a68c/raw/5b1ede8cd5bc1959a8b02b21fcc02f576eb4ef4a/municipios.json"
});

The problem, I think, should be in the format as the JSON file is (which can be seen here ).

What should be the JSON format?

    
asked by anonymous 06.12.2015 / 09:11

1 answer

1

I do not know this plugin, and looking at docs it seems to me that you have to format JSON in a certain way I do not like it :) I do not like it because it gives more work than what it takes.

Here is a suggestion without plugin, without jQuery:

var estado = document.getElementById('estado');
var municipio = document.getElementById('municipio');

function buscaJSON(url, cb) {
  var request = new XMLHttpRequest();
  request.open('GET', url, true);
  request.onload = function() {
    if (request.status >= 200 && request.status < 400) {
      var data = JSON.parse(request.responseText);
      cb(null, data);
    } else {
      cb('Error: ' + request.responseText);
    }
  };
  request.onerror = function() {
    cb('Unknown error');
  };
  request.send();
}

estado.addEventListener('change', processar);

function processar(e) {
  var estado = this.value;
  buscaJSON('https://gist.githubusercontent.com/eduardo-almeida-II/6e1caf8875949b38a68c/raw/5b1ede8cd5bc1959a8b02b21fcc02f576eb4ef4a/municipios.json', function(err, json) {
    var cidades = json[estado];
    municipio.innerHTML = '';
    cidades.forEach(function(cidade) {
      var opt = document.createElement('option');
      opt.value = opt.innerHTML = cidade;
      municipio.appendChild(opt);
    });
  });
}

jsFiddle link

The interesting part is the processar function. Then I get the value of the element that received the change event, I select the key of that state var cidades = json[estado]; in JSON and then I scroll through all the names creating a option for each ...

    
06.12.2015 / 09:25