Mysql
 sql >> Base de Dados >  >> RDS >> Mysql

Altere o valor da segunda seleção na primeira seleção


Como você disse que não tem experiência com jQuery ou Ajax, postarei minha resposta com o máximo de comentários possível. Presumirei que você tenha duas listas suspensas selecionadas em sua página.

O primeiro contém os construtores, então terá id="builders" .

O segundo contém as regiões, então terá id="regions" .

Pelo que entendi, o primeiro select será exatamente aquele que você postou na sua pergunta, gerado do lado do servidor (por PHP). Só peço que você faça uma pequena alteração nele, fazendo com que cada valor de opção seja igual ao ID do banco de dados do construtor, e não ao seu nome (a menos que a chave primária do construtor seja o nome dele, e não um ID). Isso não fará diferença para o usuário final, mas será importante para nossa solução jQuery. O segundo estará vazio, pois a ideia é preenchê-lo dinamicamente com as regiões relacionadas ao construtor selecionado no primeiro dropdown.

Agora vamos ao código jQuery:
//Everything that goes below this first line will be ready as soon as the page is fully loaded
$(document).ready(function() {
  //The following code defines an event. More precisely, we are defining that the code inside it will run every time our select with id "builders" has its value changed
  $('#builders').change(function() {
    //$(this) is our builders select. $(this).val() contains the selected value, which is the ID of our selected builder
    var currentValue = $(this).val();
    //Now, this is our Ajax command that will invoke a script called get_regions.php, which will receive the builder's ID in $_GET['builder_id'] and you can use to query your database looking for all regions related to this builder. Make sure to create an array with the returned regions. Your get_regions.php's last line should be echo json_encode($regions); 
    $.get("get_regions.php", {'builder_id': currentValue}, function(data) {
      //Inside this function is the code that will run when we receive the response from our PHP script. It contains a JSON encoded list of regions, so first of all we need to parse this JSON
      var regions = $.parseJSON(data);
      //Before filling our second select dropdown with the regions, let's remove all options it already contains, if any
      $('#regions').empty();
      //Now, all there is left is to loop over the regions, adding each as an option of the regions dropdown. I'll do it the universal way
      for (var i = 0; i < regions.length; i++) {
        var regionOption = '<option value="'+regions[i]['region_name']+'">';
        regionOption += regions[i]['region_name'];
        regionOption += '</option>';
        $('#regions').append(regionOption);
      }
    });
  });
});

Apesar de quaisquer erros de sintaxe (não é possível testar o código daqui), isso deve funcionar. Espero que os comentários tenham sido claros o suficiente para você entender como as coisas funcionam no jQuery.