Chained Select: how to select Brazilian municipalities in a JSON file from the state select

Asked

Viewed 792 times

4

EDITION

In case, 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 plugin Chained Select.

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

<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 those states related in another combo box from a JSON file.

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

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

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

What should be the JSON format?

  • 1

    Have you seen this question? -> http://answall.com/a/10766/129

  • Oh, yes! I knew it that way! It’s just that now I’m using Datatables to generate a full CRUD grid and when I get to do select chained with the Chained Select plugin will get more "clean" my code.

1 answer

2


I don’t know this plugin, and looking at the Cdocs It seems to me that you have to format JSON in a certain way that I don’t like :) I don’t like it because it is more work than necessary.

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 http://jsfiddle.net/Sergio_fiddle/6utbmzx4/

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.