Good afternoon I need to make three drop-down lists (select) in an html template where two of them depend on the first selection that is chosen.
Good afternoon I need to make three drop-down lists (select) in an html template where two of them depend on the first selection that is chosen.
The solution I found is very simple since onChange I could invoke the two javascript functions (separating them by semicolons).
I am currently using PHP, HTML and jQuery. I'll explain (in the comments of the code) the easiest way for you to understand it.
In my case, I have 2 select one that we will call Institution and another that we will call area: One that contains the name of the institutions, and that when selecting the institution, the following selection will show us the areas / careers that the institution contains.
<?php
//Hago la consulta a la base de datos de instituciones
$query = 'SELECT * from instituciones';
$result = $connection->query($query);
?>
<select class="form-control" name="institucion" id="institucion" required>
<option>Selecciona una institución</option>
<?php
//Despliego todos los registros de mi consulta con el ciclo While
while($row = $result->fetch_array()){
?>
<option value="<?php echo $row['idinstitucion']; ?>">
<?php //Muestro el nombre de la institucion
echo $row['nombre'];
?>
</option>
<?php
}
?>
<div class="form-group">
<label for="area">Area</label>
<select class="form-control" name="area" id="area" required>
<option>Selecciona el area</option>
</select>
</div>
If you notice, my first select contains an ID called institution and the second select contains an ID called area. And now the good starts with jQuery ... Inside jQuery this will go:
$(document).ready(function(){
$("#institucion").change(function(){ //Evento que se activa cuando selecciono el ID de institución
var institucion=$(this).val(); //Obtenemos el valor de institucion
//Envio a una página que hara la consulta SQL y me devolvera los datos
$.get("http://localhost/asignaturas/procesarasignaturas.php?idinstitucion="+institucion,
function(data){
$("#area").html(data); //Le decimos donde queremos mostrar el resultado que se hara en la pagina.
});
});
});
What's in procesarasignaturas.php? Well, that's where we'll do the query for our call called #area, which will be activated when we select our select called #institution.
<?php
include('connection.php');
//Obtenemos el valor del evento GET que pusimos en JQuery
$idinstitucion = $_GET['idinstitucion'];
//Hacemos nuestra consulta MySQL.
$sqlarea = "SELECT * FROM area WHERE idinstitucion='$idinstitucion'";
$consultatipo = $connection->query($sqlarea);
?>
<option>Selecciona el area</option>
<?php
while($query = $consultatipo->fetch_array()){
?>
<option value="<?php echo $query['idinstitucion']; ?>">
<?php echo $query['area'];?>
</option>
I hope and it will be of help. Please, if you have any questions, if you are not clear or something I can do, I am willing to help. Regards! : D