I have activated my js file in my Yii project view:
<?php
/* Register javascript */
Yii::app()->clientScript->registerScriptFile(Yii::app()->baseUrl . '/js/showHide.js');
?>
still in my view, I have a checkBox named 'tbo_sk' and textField named 'nilaiblksk'
<?php echo $form->checkBox($model, 'tbo_sk'); ?>
<div style="display: none"><?php echo $form->textField($model, 'nilaiblksk'); ?></div>
My question is, how do we make the javascript code in my showHide.js file, to show the textField whenever I check the checkBox, otherwise hide the textField if unchecked?
In my div tag, I'm using the style="display: none" to hide textField.
Thanks in advance!
It's better to give your div an ID or Class, rather than using parent() in jQuery:
<div id="hiddenDiv" style="display: none"><?php echo $form->textField($model, 'nilaiblksk'); ?></div>
<script>
$(document).ready(function(){
$('#MODELNAME_tbo_sk').change(function(){
$('#hiddenDiv').toggle(); // or do $('#MODELNAME_nilaiblksk').parent().toggle();
});
});
</script>
Then the view file add the following code :
Register a jquery function on document ready to toggle input:
$buttonToggler= <<<JS
toggleInput=function(src,inputName){
if(src.checked){
$(src.form[inputName]).removeProp('disabled');
}else{
$(src.form[inputName]).prop('disabled','disabled');
}
}
JS;
Yii::app()->clientScript->registerScript('toggleFormInputs',$buttonToggler, CClientScript::POS_READY);
Add function to checkbox change event:
echo $form->checkBox($model,'tbo_sk',
array('onchange'=>'js:toggleInput(this,"ModelName[nilaiblksk]")'));
echo $form->textField($model,"nilaiblksk");
you have to replace actual model name e.g "ModelName[nilaiblksk]" e.g for post model it will be "Post[nilaiblksk]", whatever the actual model you are using.
One more thing , You have to change the toggleInput function e.g if you might only want to make it readonly or add remove css class