Change the OPTION of a SELECT according to the change made in the other SELECT

Asked

Viewed 910 times

1

Hello, everyone. I have a question regarding a form.

I have a form in which your SELECT has your OPTION filled through PHP (A select made in a create file).

However, there are 3 fields (SELECT) that are interconnected. So I would like when I change one of these fields the other fields will be changed as well. Let me show you a page print.

inserir a descrição da imagem aqui

Above, we have the fields COD, COMPANY and TAXATION. In the database, each company has a code (which is the COD field) and taxation (which is the field TAXATION).

I would like that when I change the COD field, the COMPANY field select goes to the company (option) corresponding to the COD field code and vise and versa.

Below follows the SELECT padding code.

<!-- LINHA -->
                        
<div class="col-lg-12 alinhar-texto-no-centro" id="selecionar-empresas">
  <h3 class="alinhar-texto-no-centro">Selecionar Empresa</h3>

  <!-- CAMPO CODIGO DA EMPRESA -->
  <div class="form-group col-lg-2">

    <label for="codigo-empresa">COD</label>
    <select name="codigo-empresa" id="codigo-empresa" class="input form-control">
      <?php
      $i = 1;
      while($registros = $query_pegar_cod -> fetch_assoc())
      {                                                                                     
        $emp = $registros['COD'];
        echo "<option id='$i'>$emp</option>";
        $i++;                                           
      }
      ?>            
    </select>

  </div>

  <!-- CAMPO EMPRESA -->
  <div class="form-group col-lg-5">
    <label for="empresa">Empresa</label>
    <select name="empresa" id="empresa" class="input form-control">
      <?php
      $j = 1;

      while($registros = $query_pegar_empresa -> fetch_assoc())
      {
        $empr = utf8_decode($registros['EMPRESAS']);
        echo "<option id='$j'>$empr</option>";                                          
      $j++;
      }
      ?>                    
    </select>
  </div>

  <!-- CAMPO TRIBUTAÇÃO -->
  <div class="form-group col-lg-5">
    <label for="tributacao">Tributação</label>
    <select name="tributacao" id="tributacao" class="input form-control">
      <?php
        while($registros = $query_pegar_tributacao -> fetch_assoc())
        {
          $empre = utf8_decode($registros['TRIBUTACAO']);
          echo "<option>$empre</option>";
        }
      ?>                                
    </select>
  </div>

I know the explanation wasn’t so succinct, but I hope you can understand.

Thank you!

  • Just make an ajax call to the PHP server at the event onchange of the first <select> which must return the data needed to fill in the second and third <select>. Add the code you’ve tried

  • Guilherme, you say the code I’ve tried in ajax ? I’ve tried some things, but by not working out I ended up erasing. Could you suggest something regarding jquery, ajax ... that I could use ? I will edit the question and add the code of how I filled the selects.

2 answers

0

You will need to use AJAX to do this

var url = ENDEREÇO DA REQUISIÇÃO; //se utiliza MVC aqui você chama o controller
var dado = DADOS_QUE_SERÃO_PASSADOS_PELO_POST; //ou get caso o type for get 

$.ajax({
    type: "POST",
    url: url,
    data: dado,
  }).done(function(resultado) {

  }).fail(function() {

  });

Within the function done in the code above you have the return of your request, so just take this value and using the popular jquery the desired select.

  • Man, sorry for my lack of knowledge, but your answer was not very clear to me. I’m not very used to using ajax. Could you clarify or suggest something just using jquery ?

  • 1

    @Thiagopetherson is that the only way (as far as I know) you can make this query and play on the screen WITHOUT UPDATING the page, is by using AJAX. Or have all this information already when opening the page(gambiarra). Try to read this: https://www.devmedia.com.br/ajax-tutorial/24797 and see if you can, I could give you more attention, but right now I’m a little stuck here.

  • So, Octavian. I don’t think you understand. The page, when loaded, already comes with information filled in the fields (according to the login made by the user). For example, such an employee has some companies, while another employee does not. And this initial fill is done with PHP, through a select. What I would like, is just in those 3 specific fields, when I change one field, the other one changes automatically. I know I could do a query via ajax with POST. But in my case, I think it would be more appropriate using jQuery’s CHANGE. What do you think ?

0

Actually I believe there are 2 ways to solve this problem:

  • The first and I believe it is the best way to use ajax as colleague @Otavio replied you put an event .change() in the COD select and when changing this select run an ajax that does a database search and fill in the next select.

  • The second would be less efficient, would be to have an event .change() in the COD, and the others select's already populated occult (i.e., with the display : none;), when the event .change() was triggered, one of the select's would be shown with the function .show().

As @Otavio already exemplified the first method, I’ll leave the second one here.

<!DOCTYPE html>
<html>
<head>
    <title>Teste otávio</title>
    <meta charset="utf-8">
    <script
    src="https://code.jquery.com/jquery-3.3.1.js"
    integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
    crossorigin="anonymous"></script>
</head>
<body>
    <select id="select">
        <option value="" selected>Selecione</option>
        <option value="selectA">Select A</option>
        <option value="selectB">Select B</option>
        <option value="selectC">Select C</option>
    </select>
    <select id="selectA" class="opicionais" style="display: none;">
        <option value="opA1">Opção A1</option>
        <option value="opA2">Opção A2</option>
        <option value="opA3">Opção A3</option>
    </select>
    <select id="selectB" class="opicionais" style="display: none;">
        <option value="opB1">Opção B1</option>
        <option value="opB2">Opção B2</option>
        <option value="opB3">Opção B3</option>
    </select>
    <select id="selectC" class="opicionais" style="display: none;">
        <option value="opC1">Opção C1</option>
        <option value="opC2">Opção C2</option>
        <option value="opC3">Opção C3</option>
    </select>

</body>
</html>
    <script type="text/javascript">
        $("#select").change(function(){
            $(".opicionais").each(function(){
                $(this).hide();
            });
            var valor = $(this).val();
                $("#"+valor).show();
        });
    </script>

Browser other questions tagged

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