Show And Hide Textfield Using Checkbox With Javascript Method

This is how we show or hide textField by clicking a checkBox using javascript method.

First we create a javascript file named showHide.js for example, and save it to our js folder. Inside it, we put the code as follows:




$(document).ready(function(){

    $('#Dcl_tbo_sk').change(function(){ // where Dcl_tbo_sk is my model & table (model_table)

        $('#Dcl_nilaiblksk').parent().toggle(); // same here, Dcl_nilaiblksk is my model & table (model_table)

    }); 

});



We may use the $(’#Dcl_nilaiblksk’).parent().toggle(); method, but it is best to make ID for the div tag’s id (e.g #hiddenDiv)

So the code will be modified as follows:




$(document).ready(function(){

    $('#Dcl_tbo_sk').change(function(){ // where Dcl_tbo_sk is my model & table (model_table)

        $('#hiddenDiv').toggle(); // hiddenDiv replace our Dcl_nilaiblksk as model & table (model_table)

    }); 

});



If we notice, the .parent() is not included anymore since have our div id.

Then, inside our view we register the javascript file (showHide.js):




<?php

/* Register javascript */

Yii::app()->clientScript->registerScriptFile(Yii::app()->baseUrl . '/js/showHide.js');

?>



Still in the same view file, we add the checkBox and textField:




<?php  echo $form->checkBox($model, 'tbo_sk'); ?> // our checkBox


<div id="hiddenDiv" style="display: none">

       <?php echo $form->textField($model, 'nilaiblksk'); ?> // our textField

</div>



There we have it!

nice…

Thanks, hope it will be useful.

Registered specially for this comment.

Thanks, Larry Jr., very useful!