JSON States and Cities Select ZIP Problem

Asked

Viewed 395 times

1

Good afternoon,

I’m having a problem with my select of states and cities.

When I type one ZIP CODE it fills in the fields automatically, I can already fill in the State even though he is a select and even better not needing to set the acronyms of States in "option value", however the city is not selected, see well: it is displayed in the field below or the link between city and state is working, but it does not arrow the city that was received from the ZIP code, below the codes:

cep.js

$("#cep_res").blur(function() {

var url = "http://cep.republicavirtual.com.br/web_cep.php";
var cep = $(this).val();

 $.ajax({
    type: "GET",
    dataType: 'json',
    data: {'cep': cep, 'formato': 'json'},
    async: false,
    url: url,
    success: function(response) {

        if (response.resultado === '1') {

            $("#bairro_res").val(response.bairro);
            $("#logradouro_res").val(response.logradouro);

            var uf = response.uf;
            $("select#estado_ress option").each(function() {
                this.selected = (this.text === uf);
            });

            var cidade = response.cidade;
            $("select#cidade_ress option").each(function() {
                this.selected = (this.text === cidade);
            });

            $("#estado_ress").trigger("change");

        }

    }
 });

});

php form.

        <label>Estado <span>*</span></label>
        <select class="classic" name="estado_res" id="estado_ress">
            <option value="0">Selecione</option>
            <?php
                $q = "SELECT * FROM estado ORDER BY nome";
                $g = connect($q);
                while($e = mysql_fetch_assoc($g[0])){
                    echo '<option value="'.$e['id'].'">'.$e['uf'].'</option>';
                }
            ?>
        </select>
        <script>
            $(document).ready(function(){
                $('#estado_ress').change(function(){
                    var param = $(this).val();

                    $.post("../escola/busca_cidade.php", { est: param }, function(valor){
                            $("#aqui_cidadec").html(valor);

                        }

                    );
                });
            });
        </script>
        <div id="aqui_cidadec">
            <label>Cidade <span>*</span></label>
            <select class="classic" name="cidade_res" id="cidade_ress" style="text-transform:none !important;">
                    <option value="0">Selecione</option>
            </select>
        </div>

busca_cidade.php

<?php

require_once('./lib/classes/conexao.php'); 
require_once('./lib/functions/functions.func.php'); 
require_once('./lib/classes/mysql.class.php');
if(!empty($_REQUEST['est'])){

    $q = "SELECT * FROM cidade WHERE estado = '".$_REQUEST['est']."'";
    $g = connect($q);
    echo '<label>Cidade <span>*</span></label>';
    echo '<select class="classic" name="cidade_res" id="cidade_ress">
                <option value="0">Selecione</option>';

    while ( $l = mysql_fetch_assoc($g[0]) ) {
        echo '<option value="'.$l['id'].'">'.$l['nome'].'</option>';
    }
    echo '</select>';
} else { ; }
?>

At the end of php form. i have the following script:

<script src="<?php echo $url_site; ?>lib/js/cep.js" type="text/javascript"></script>

Who has suggestions of what can be done or some mistake I made, can comment there!

  • I found someone with a similar problem, but for me the assigned solution didn’t work: https://answall.com/questions/5968/assignr-item-selected-em-um-select

1 answer

0


It is not recommended to use async: false. See why in this question.

This is because you are wanting to take the city before suing the Ajax that changes the state and populates the select cities, so the code does not know which option select.

You need to tie the bow...

$("select#cidade_ress option").each(function() {
    this.selected = (this.text === cidade);
});

...after the select cities to be populated. Do the following: send the city value as parameter of the trigger to the Ajax of the states and put the noose on that Ajax:

var cidade = response.cidade;
$("#estado_ress").trigger("change", cidade);

And in Ajax of the States (event change), receive the value cidade sent by trigger and make the loop:

$('#estado_ress').change(function(e, cidade){
   var param = $(this).val();

   $.post("../escola/busca_cidade.php", { est: param }, function(valor){
      $("#aqui_cidadec").html(valor);

      $("select#cidade_ress option").each(function() {
         this.selected = (this.text === cidade);
      });

   });
});

In short, the ZIP code Ajax would look like this:

$.ajax({
    type: "GET",
    dataType: 'json',
    data: {'cep': cep, 'formato': 'json'},
    async: false,
    url: url,
    success: function(response) {

        if (response.resultado === '1') {

            $("#bairro_res").val(response.bairro);
            $("#logradouro_res").val(response.logradouro);

            var uf = response.uf;
            $("select#estado_ress option").each(function() {
                this.selected = (this.text === uf);
            });

            var cidade = response.cidade;

            $("#estado_ress").trigger("change", cidade);

        }

    }
 });

});

And that of the States thus:

$('#estado_ress').change(function(e, cidade){
   var param = $(this).val();

   $.post("../escola/busca_cidade.php", { est: param }, function(valor){
      $("#aqui_cidadec").html(valor);

      $("select#cidade_ress option").each(function() {
         this.selected = (this.text === cidade);
      });

   });
});

Edit

Function to remove accents from city names:

function remAcentos(p){

   var acc = {
      'â': 'a', 'à': 'a', 'ã': 'a', 'â': 'a', 'á': 'a',
      'é': 'e', 'ê': 'e',
      'í': 'i',
      'ó': 'o', 'õ': 'o', 'ô': 'o',
      'ú': 'u'
   }

   return p.replace(/[áàãâéêíóõôú]/g, function(m){
      return acc[m];
   });

}

To use the function, include the variable cidade when calling her:

$('#estado_ress').change(function(e, cidade){

      cidade = remAcentos(cidade); // AQUI REMOVE OS ACENTOS

      $("select#cidade_ress option").each(function() {
         this.selected = (this.text.toLowerCase() === cidade);
      });

});

It is also interesting to add a toLowerCase() here:

this.selected = (this.text.toLowerCase() === cidade);

Because it may be that some city can come with a capital letter. With toLowerCase() this problem is circumvented.

  • It worked right here man! That’s exactly what was happening then, I didn’t pay attention to the ties! Just one more thing, my database is with all cities without accentuation so when I type the zip code of a city that has accent, the value does not match because it is coming there from the query in ajax with accent and in my bank is without accent, then it does not select! How can I get around this? Thanks so much for the help! I was already going crazy with these selects

  • Relax, I’ll put in the answer in a little while what you can do to solve the problem of accents.

  • See there, I put a function just for that. It’s good that you can use it whenever you want to remove accents.

  • Make sure to mark the answer. Abs!

  • Ball show! It worked here.It’s already marked! And thank you again friend!

Browser other questions tagged

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