Make Form Element Disappear Based On Dropdown Selection

I have model create form (to create a new user) and I would like to make one of the form elements appear only when a certain item is selected in a dropdown select menu.

I think jquery is the best way probably but I’ve not found much on how to create jquery functions and including them using the yii framework.

This one seems to stop after a very very short introduction on how to get ‘hello’ alert working:

http://usingjquery.com/2010/10/using-jquery-with-the-yii-framework/





<?php

    Yii::app()->clientScript->registerScript('helloscript',"

        alert('hello');

    ",CClientScript::POS_READY);

?>



I need to create a function that will trigger when the dropdown select changes value, how to do this in yii?

any help much appreciated,

thanks

gvanto

This should help give you an idea,




$(function() {

  $('#mydropdown').on('change', function() {

    $('#otherfield').css('display', ('myval' === $(':selected', this)) ? 'block' : 'none');

  });

});




<?php

    Yii::app()->clientScript->registerScript('helloscript',"

        $(document).on('change', '#id-of-dropdown', function() {

            $('#if-of-element').toggle($(this).val() == dropdown_value_that_you_want_to_match);

        });

    ",CClientScript::POS_READY);

?>

Thats really great, its works nicely, but i have ‘bodged’ a default hidden by adding style=“display:none” to the DIV thats being toggled… :-X

Also, if i then go back into the form, the div is hidden (obviously) to show it again to edit the value of the form element, I have to ‘change’ the drop down to ‘toggle’ the hidden div…

how can I set it to show the field if its been used, uhm, this sort of thing easier to explain in code if ( #id-of-dropdown == ‘xyz’) { show(); }

Or if #id-of-element !empty()…

Like this?


    $(document).on('change', '#id-of-dropdown', function() {

        if ($(this).val() == dropdown_value_that_you_want_to_match) {

            $('#id-of-element').show();

        } else {

            $('#id-of-element').hide();

        }

    });