Pass selected values in a select to a div

Asked

Viewed 44 times

2

I am 02 selects that when selecting the city of the first, automatically fills the state of the other. See:

<select name='Cidade' id='cidade' class="form-control" required='required'>
     <option>Selecione a cidade</option>
     <option value="RJ">Rio de Janeiro</option>
     <option value="SP">São Paulo</option>
</select>

<script type=\"text/javascript\">
$(function(){
    $('#cidade').change(function(){
        if( $(this).val() ) {
            $('#estado').hide();
            $('.carregando').show();
    $.getJSON('listar-estados.php?search=',{series: $(this).val(), ajax: 'true'}, function(j){
                var options = '';
                for (var i = 0; i < j.length; i++) {
                    options += '<option value=\"' + j[i].id + '\">' + j[i].estado + '</option>';
                }
                $('#estado').html(options).show();
                $('.carregando').hide();
            });
        } else {
            $('#estado').html('<option value="">– Escolha o estado –</option>');
        }
    });
});
</script>

The states comes from the Mysql database and is listed in PHP:

<?php
    public function listarEstados($idCidades){

    $sqlEstados = mysqli_query($this->conexao,"SELECT * FROM estados WHERE Cidades = '".$idCidades."';");

       while($peEstados = mysqli_fetch_assoc($sqlEstados)){
              $listarEstados[] = array(
                  'id'  => $peCidades['$idEstados'],
                  'estados' => utf8_encode($peEstados['Estados']),
              );
         }
       return (json_encode($listarEstados));
    }
?>

THE HTML:

<div class="form-group">
    <span class="carregando">Aguarde, carregando...</span>
    <label for="estado" class="control-label">Estado: <span style="color: red">*</span></label>
         <select name="Estado" id="estado" class="form-control" >
        <option>Selecione a cidade acima</option>
    </select>
</div>

It works perfectly, but how could I pick the selected value in the state (second select) and play for the jquery below?

var estadousuario = document.querySelector('#estadousuario');
var paragrafoEstadoUsuario = document.querySelector('#paragrafoestadousuario');
estadousuario.addEventListener('keyup', function () {
paragrafoEstadoUsuario.innerHTML = "<input maxlength='200' type='text' ='' class='form-control' value='" + estadousuario.value + "' disabled />";
  • Why use the array values = [];? The intention is a multiple choice select?

  • Hello sam. I adjusted my post.

2 answers

3


There are some errors in the code:

In the for you’re picking up j[i].estado ("singular" state) of the return of Ajax, and in PHP is returning 'estados' => ("states" in plural). This results in Undefined.

Change the line in PHP to:

'estado' => utf8_encode($peEstados['Estados']),

Here: document.querySelector('#estadousuario'); you are selecting a id that does not exist. The id of select is #estado, then the right thing would be:

var estadousuario = document.querySelector('#estado');

To take the value of select, don’t use the event keyup, and yes change:

estadousuario.addEventListener('change', function () {...

With these fixes it will work:

var estadousuario = document.querySelector('#estado');
var paragrafoEstadoUsuario = document.querySelector('#paragrafoestadousuario');
estadousuario.addEventListener('change', function () {
   paragrafoEstadoUsuario.innerHTML = "<input maxlength='200' type='text' ='' class='form-control' value='" + estadousuario.value + "' disabled />";
});

$(function(){
   $('#cidade').change(function(){
      if( $(this).val() ) {
         $('#estado').hide();
         $('.carregando').show();
         $.getJSON('listar-estados.php?search=',{series: $(this).val(), ajax: 'true'}, function(j){
            var options = '';
            for (var i = 0; i < j.length; i++) {
               options += '<option value=\"' + j[i].id + '\">' + j[i].estado + '</option>';
            }
            $('#estado').html(options).show();
            $('.carregando').hide();
         });
      } else {
         $('#estado').html('<option value="">– Escolha o estado –</option>');
      }
   });
});

You can use the event change in jQuery, it becomes simpler the code:

Change:

var estadousuario = document.querySelector('#estado');
var paragrafoEstadoUsuario = document.querySelector('#paragrafoestadousuario');
estadousuario.addEventListener('change', function () {
   paragrafoEstadoUsuario.innerHTML = "<input maxlength='200' type='text' ='' class='form-control' value='" + estadousuario.value + "' disabled />";
});

For:

$('#estado').on("change", function(){
   $('#paragrafoestadousuario').html("<input maxlength='200' type='text' ='' class='form-control' value='" + this.value + "' disabled />");
});
  • Right. I did exactly as you passed, but it’s returning null.

  • Is that because the values are coming from the BD and returning json_encode(), would not be conflicting?

  • Yes they are... appear normally....

  • This... appears in select, but does not show in paragraph. Shows as null.

  • 1

    Dude, after choosing a city and popular the states, goes on "inspect elements" of the browser and Inspecione that select of the states. See if you are returning the right values.

  • Bingo Sam. Exactly that... forgive me for the setback. It was a failure of mine here, but your code worked perfectly. Thank you very much!

  • 1

    Good. Rs.. Good luck!

Show 2 more comments

1

Good night buddy,

You can follow the same one that was already made for the city by adding an event of change() in the selectBox state:

    $('#estado').change(function () {
        var estadoSelecionado = $(this).val();
        
        //Faça o que quiser aqui
    }

  • Good evening Victor. Forgive me, I forgot to put the rest of the code. The states comes from the database. I changed my post.

  • And when I use your code, it returns null.

Browser other questions tagged

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