Añade un listener del evento change al primer select. Cuando cambie, lee su valor, envíalo al servidor mediante una petición AJAX y usa la respuesta para rellenar el segundo desplegable. Aquí tienes un ejemplo funcional para seleccionar ciudades según el país elegido:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Populate City Dropdown Using jQuery Ajax</title> <script type="text/javascript" src="https://code.jquery.com/jquery.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("select.country").change(function(){ var selectedCountry = $(".country option:selected").val(); $.ajax({ type: "POST", url: "process-request.php", data: { country : selectedCountry } }).done(function(data){ $("#response").html(data); }); }); }); </script> </head> <body> <form> <table> <tr> <td> <label>Country:</label> <select class="country"> <option>Select</option> <option value="usa">United States</option> <option value="india">India</option> <option value="uk">United Kingdom</option> </select> </td> <td id="response"> <!--Response will be inserted here--> </td> </tr> </table> </form> </body> </html>
Backend:
<?php if(isset($_POST["country"])){ // Capturar el país seleccionado $country = $_POST["country"]; // Definir el array de países y ciudades $countryArr = array( "usa" => array("New Yourk", "Los Angeles", "California"), "india" => array("Mumbai", "New Delhi", "Bangalore"), "uk" => array("London", "Manchester", "Liverpool") ); // Mostrar el desplegable de ciudades según el país if($country !== 'Select'){ echo "<label>City:</label>"; echo "<select>"; foreach($countryArr[$country] as $value){ echo "<option>". $value ."</option>"; } echo "</select>"; } } ?>
El manejador .change() de jQuery dispara la llamada AJAX, y el script PHP devuelve las opciones de ciudad correspondientes, que se inyectan en la celda de respuesta.