Hide/Show element depending on dropdown selection [solved]

Hey guys. Im trying to hide 2 dependent dropdownlist and it’s labels and show them only when user selects ‘apoderado’ in the first dropdownlist.

here’s the code, I hope someone can help me 'cause I’m new to jquery and js.

RegisterAsset.php

<?php

namespace app\assets;

use yii\web\AssetBundle;

class RegisterAsset extends AssetBundle
{
    public $basePath = '@webroot';
    public $baseUrl = '@web';
    public $css = [
    ];
    public $js = [
        'js/esconderDropDownList.js',
    ];
    public $depends = [
        'yii\web\YiiAsset',
        'yii\web\JqueryAsset',
        'yii\bootstrap\BootstrapAsset',        
    ];
}

esconderDropDownList.js

$(document).ready(function(){
    $('#formregister-role').on('change', function() {
        if ($(this).val() == 1){
                    $("#formregister-id_curso, #formregister-id_alumno").show();
                } else {
                    $("#formregister-id_curso, #formregister-id_alumno").hide();
        }
    });
});

register.php

<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\helpers\ArrayHelper;
use app\assets\RegisterAsset;

RegisterAsset::register($this);
?>

<h3><?= $msg ?></h3>

<h1>Registrar Usuario</h1>
<?php $form = ActiveForm::begin([
    'method' => 'post',
 'id' => 'formulario',
 'enableClientValidation' => false,
 'enableAjaxValidation' => true,
]);
?>

<?php $tipo_usuario = [1 => 'Apoderado', 2 => 'Profesor']; ?>

<div class="form-group">
<?= $form->field($model, "role")->dropDownList($tipo_usuario, 
        [
            'prompt' => 'Seleccione tipo de usuario',
    ]); 
 ?>
</div>

<div class="form-group">
<?= $form->field($model, 'id_curso')->dropDownList(

ArrayHelper::map(app\models\Curso::find()->all(),'id', 'id'),
            [
                'prompt' => 'Seleccione un curso',
                'onchange' => '$.post("index.php?r=site/listar&id=' . '"+$(this).val(), function(data){
                    $("select#formregister-id_alumno").html(data);
                });',    
                
            ]); ?>
</div>
    
<div class="form-group">
<?= $form->field($model, 'id_alumno')->dropDownList(

ArrayHelper::map(app\models\Alumno::find()->all(),'id', 'nombre'), 
            [
                'prompt' => 'Seleccione un alumno',
            ]); ?>
</div>
    
<div class="form-group">
 <?= $form->field($model, "username")->input("text") ?>   
</div>

<div class="form-group">
 <?= $form->field($model, "email")->input("email") ?>   
</div>

<div class="form-group">
 <?= $form->field($model, "password")->input("password") ?>   
</div>

<div class="form-group">
 <?= $form->field($model, "password_repeat")->input("password") ?>   
</div>

<?= Html::submitButton("Registrar", ["class" => "btn btn-primary"]) ?>

<?php $form->end() ?>

@c.reyes.suazo Lo que necesitas es tener ambos combos el ultimo le das el atributo “disabled”, seguido al seleccionar el primero y que el valor seleccionado no sea nulo haces un evento “Ajax” al servidor para que consulte los datos del siguiente combo con la clausula “Where” con el valor del primer combo y los resultados los envías en formato “json” al cliente apuntando los datos al ultimo combo.

Would you please rewrite your reply in English?
We use English everywhere in this forum except for “International” section.

@softtark sorry, my another reply as:

What you need is to have both combos the last you give the attribute “disabled”, followed by selecting the first and that the selected value is not null you make an event “Ajax” to the server so that it can consult the data of the following combo with the clause " Where “with the value of the first combo and the results you send them in” json "format to the client pointing the data to the last combo.

1 Like

@Eloy-Gonzalez thank you for your answer but I still dont understand your solution.

@softark you’ve helped me a lot in other topics. I’ve managed to hide the dropdownlists when user selects ‘apoderado’ in the first dropdown but the labels are still there. Got any thoughts on this one? I also need to hide them until user selects ‘apoderado’. <style=“display:none”> hides both, dropdowns and labels but won’t let me display them with the script.

I solved this putting an id in both dependent dropdownlists divs and changing my js file to edit div style as seen below.

register.php

<div class="form-group">
<?= $form->field($model, "role")->dropDownList($tipo_usuario, 
        [
            'prompt' => 'Seleccione tipo de usuario',

            
    ]); 
 ?>
</div>

<div class="form-group" id="curso" style="display:none">
<?= $form->field($model, 'id_curso')->dropDownList(

ArrayHelper::map(app\models\Curso::find()->all(),'id', 'id'),
            [
                'prompt' => 'Seleccione un curso',
                'onchange' => '$.post("index.php?r=site/listar&id=' . '"+$(this).val(), function(data){
                    $("select#formregister-id_alumno").html(data);
                });',    
                
            ]); ?>
</div>
    
<div class="form-group" id="alumno" style="display:none">
<?= $form->field($model, 'id_alumno')->dropDownList(

ArrayHelper::map(app\models\Alumno::find()->all(),'id', 'nombre'), 
            [
                'prompt' => 'Seleccione un alumno',
            ]); ?>
</div>

esconderDropDownList

$(document).ready(function(){
    $('#formregister-role').on('change', function() {
        if ($(this).val() == 1){
                    document.getElementById("curso").style.display = "block";
                    document.getElementById("alumno").style.display = "block";
                } else {
                    document.getElementById("curso").style.display = "none";
                    document.getElementById("alumno").style.display = "none";
        }
    });
});
1 Like

@jc.reyes.suazo

Check this code script

View with inputs dropdown list

<?= Html::label('Estado')?><br>
<?= Html::activeDropDownList($model, 'estado_id', ArrayHelper::map(CatalogoEstado::find()->all(), 'id', 'descripcion'), ['class' => 'form-control', 'prompt' => 'SELECCIONE']) ?>
<?= $form->field($model, 'municipio_id')->dropDownList([], ['prompt' => 'SELECCIONE'])?>
<?= $form->field($model, 'parroquia_id')->dropDownList([], ['prompt' => 'SELECCIONE'])?>

<?php 

$js = <<<'JS'

// Obtener la id del elemento seleccionado de la lista desplegable
        $("#estructurasede-estado_id").on('change', function()
        {
            // Si el valor del id seleccionado no es nulo 
            if($(this).val() != null)
            {
                // Se ejecuta el ajax al servidor con los parametros establecidos
                $.ajax({
                        url: "/estructura/sede/consulta1",              // Url del modulo, clase y metodo a donde se envian los datos vía ajax
                        type: "POST",                                   // Tipo de envio (POST) o (GET)
                        data: {estado_id : $(this).val()},              // Datos a enviar al servidor donde {nombre de la variable : valor del campo o input}
                        dataType: "JSON"                                // Tipo de retorno de datos desde el servidor   
                        })
                .done(function(data)                                    // Cuando el servidor responda correctamente (Código 200) Se ejecuta el siguiente bloque de código
                { 
                    $("#estructurasede-municipio_id").html(data);       // Se escribe en el DOM los datos enviados desde el servidor.
                    $("#estructurasede-parroquia_id").html('');
                    $("#estructurasede-ciudad_id").html('');
                })
            }
        });

        // Obtener el valor seleccionado cada vez que cambia el select
        $("#estructurasede-municipio_id").on('change', function()
        {
            // Si el valor de el id seleccionado no es nulo 
            if($(this).val() != null)
            {
                // Se ejecuta el ajax al servidor con los parametros establecidos
                // console.log($(this).val());
                $.ajax({
                    url: "/estructura/sede/consulta2",              // Url donde se envian los datos vía ajax
                    type: "POST",                                   // Tipo de envio (POST) o (GET)
                    data: {municipio_id : $(this).val()},           // Datos a enviar al servidor donde {nombre de la variable : valor del campo o input}
                    dataType: "JSON"                                // Tipo de retorno de datos desde el servidor
                })
                .done(function(data)                                // Cuando el servidor responda correctamente (Código 200) Se ejecuta el siguiente bloque de código
                {
                    $("#estructurasede-parroquia_id").html(data);   // Se escribe en el DOM los datos enviados desde el servidor.
                })
            }
        });

        // Obtener el valor seleccionado cada vez que cambia el select
        $("#estructurasede-municipio_id").on('change', function()
        {
            // Si el valor de el id seleccionado no es nulo 
            if($(this).val() != null)
            {
                // Se ejecuta el ajax al servidor con los parametros establecidos
                // console.log($(this).val());
                $.ajax({
                    url: "/estructura/sede/consulta3",              // Url donde se envian los datos vía ajax
                    type: "POST",                                   // Tipo de envio (POST) o (GET)
                    data: {municipio_id : $(this).val()},           // Datos a enviar al servidor donde {nombre de la variable : valor del campo o input}
                    dataType: "JSON"                                // Tipo de retorno de datos desde el servidor
                })
                .done(function(data)                                // Cuando el servidor responda correctamente (Código 200) Se ejecuta el siguiente bloque de código
                {
                    $("#estructurasede-ciudad_id").html(data);      // Se escribe en el DOM los datos enviados desde el servidor.
                })
            }
        });
JS;

$this->registerJs($js);

 ?>


Perform send vía Ajax values selected from first input dropdown to controller and get results from server in format json to set in secound dropdown input

Controller

 public function actionConsulta1()
    {
        // Se obtienen los datos de la consulta y se almacenan en la variable
        $consulta = (new Query())
                ->select('id, descripcion')
                ->from('catalogo.municipio')
                ->where(['estado_id' => $_POST['estado_id']])
                ->orderBy('id ASC')
                ->all();
    
        // Se crea una variable con informacion del select 
        $opciones = "<option value='' selected>Seleccione</option>";

        // Se itera sobre el arreglo y se definen las variables a enviar por ajax
        foreach($consulta as $consulta)
        {
            $opciones.='<option value='.$consulta['id'].'>'.$consulta['descripcion'].'</option>';
        }

        // Se envian cabeceras en formato JSON vía ajax
        echo json_encode($opciones);
    }

    public function actionConsulta2()
    {
        // Se obtienen los datos de la consulta y se almacenan en la variable
        $consulta = (new Query())
                ->select('id, descripcion')
                ->from('catalogo.parroquia')
                ->where(['municipio_id' => $_POST['municipio_id']])
                ->orderBy('id ASC')
                ->all();
    
        // Se crea una variable con informacion del select 
        $opciones = "<option value='' selected>Seleccione</option>";

        // Se itera sobre el arreglo y se definen las variables a enviar por ajax
        foreach($consulta as $consulta)
        {
            $opciones.='<option value='.$consulta['id'].'>'.$consulta['descripcion'].'</option>';
        }

        // Se envian cabeceras en formato JSON vía ajax
        echo json_encode($opciones);
    }

    public function actionConsulta3()
    {
        // Se obtienen los datos de la consulta y se almacenan en la variable
        $consulta = (new Query())
                ->select('id, descripcion')
                ->from('catalogo.ciudad')
                ->where(['municipio_id' => $_POST['municipio_id']])
                ->orderBy('id ASC')
                ->all();
    
        // Se crea una variable con informacion del select 
        $opciones = "<option value='' selected>Seleccione</option>";

        // Se itera sobre el arreglo y se definen las variables a enviar por ajax
        foreach($consulta as $consulta)
        {
            $opciones.='<option value='.$consulta['id'].'>'.$consulta['descripcion'].'</option>';
        }

        // Se envian cabeceras en formato JSON vía ajax
        echo json_encode($opciones);
    }

PD: Check´s id´s from inputs, im using ActiveForm