简体   繁体   中英

Yii2 - Show form fields based on dropDownList

I have the following dropDownList

<?= $form->field($model, 'moradaalternativa')
    ->dropDownList(
        [
        'Não' => 'Não',
        'Sim' => 'Sim'],
        ['prompt'=>'Faça a sua escolha'],
    );
?>

What i'm trying to do is: If the value is = Sim, then some other form fields that are hidden by a css class show up below the dropDownList, and if the value is = Não, then the form fields hide from the page again.

I know that there is a 'onchange' property like javascript but i don't know how to apply it to this effect or even if i need to use it.

Any ideas?

It's pretty simple, all you need is:

$(document).ready(function () {
    $(document.body).on('change', '#your-id', function () {
        var val = $('#your-id').val();
        if(val > 0 ) {
          $('.class').hide();
        } else {
          $('.class').show();
        }
    });
});

And just change the names as needed. For Yii2 you can wrap it, then you can just put the code in a view file but it's better to put it in a JS file:

<?php
$script = <<< JS

code here

JS;
$this->registerJs($script);
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM