sql >> Base de Datos >  >> RDS >> Mysql

Cambiar el valor de la segunda selección en la primera selección

Como dijiste que no tienes experiencia con jQuery o Ajax, publicaré mi respuesta con tantos comentarios como sea posible. Asumiré que tiene dos menús desplegables de selección en su página.

El primero contiene los constructores, por lo que tendrá id="builders" .

El segundo contiene las regiones, por lo que tendrá id="regions" .

Por lo que entiendo, la primera selección será exactamente la que publicó en su pregunta, generada en el lado del servidor (por PHP). Solo le pido que haga un ligero cambio en él, haciendo que el valor de cada opción sea igual al ID de la base de datos del constructor y no a su nombre (a menos que la clave principal del constructor sea su nombre y no un ID). Esto no supondrá ninguna diferencia para el usuario final, pero será importante para nuestra solución jQuery. El segundo estará vacío, ya que la idea es llenarlo dinámicamente con las regiones relacionadas con el constructor seleccionado en el primer menú desplegable.

Ahora vayamos al 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);
      }
    });
  });
});

A pesar de cualquier error de sintaxis (no se puede probar el código desde aquí), esto debería funcionar. Espero que los comentarios hayan sido lo suficientemente claros para que entiendas cómo funcionan las cosas en jQuery.