city state JQuery selection error

4

JQuery:

$(function() {
  $(document).delegate('#estado', 'change', function() {
    var valor = $('#estado').val();
    $('#cidade').load('_requires/cidades.php?estado=' + valor );
   });

  $(document).delegate('#cidade', 'change', function() {
    var valor = $('#cidade').val();
    alert(valor);
    $('#bairro').load('_requires/bairros.php?cidade=' + valor );
   });

 });

HTML:

<div>
   <label class="labelPequena">Estado</label><br />
   <select class="typeTextMedio" id="estado" name="estado" required>
      <option value="">Escolha o Estado</option>
      <option value="MG">MG</option>
      <option value="ES">ES</option>
      <option value="RJ">RJ</option>
      <option value="SP">SP</option>         
   </select>
</div>

<div>
   <label class="labelPequena">Cidade</label><br />
   <select class="typeTextMedio" id="cidade" name="cidade" required>
      <option value="">Escolha a Cidade</option>         
   </select>
</div>

<div>
   <label class="labelPequena">Bairro</label><br />
   <select class="typeTextMedio" id="bairro" name="bairro" required>
     <option value="#">Indiferente</option>

   </select>
</div>

When you select in combo estados , popular combo cidades . This is working.

When you select in combo cidades , popular combo bairro . This is NOT working. But I noticed that in% w / w% only ERR occurs with the first city only, and when I click on it, the event does not occur. With the others it usually occurs.

An important observation is that if you choose second city of combo cidades , and combo of neighborhoods are loaded, then go back and select the first city again, so now it works. On the first try neither combo works!

How to solve?

    
asked by anonymous 27.04.2016 / 16:52

1 answer

2

The problem is occurring because you are not returning along with the results of the cities the option Choose the City. This way the first city comes by default as selected but without activating the combo change.

Another way to solve the problem is to change the javascript combo code #State to:

$(document).delegate('#estado', 'change', function() {
    var valor = $('#estado').val();
    $('#cidade').load('_requires/cidades.php?estado=' + valor, function() {
       $('#cidade').trigger('change');
   });

 });

Note that the trigger will invoke the change event in the #city combo.

    
27.04.2016 / 17:25