如何在Yii javascript中使用checkBox隐藏或显示textField
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!
我在Yii项目视图中激活了我的js文件: p>
&lt;?php / *注册javascript * / Yii :: app() - &gt; clientScript-&gt; registerScriptFile(Yii :: app() - &gt; baseUrl。'/ js / showHide.js') ; ?&gt; code> pre>仍然在我的视图中,我有一个名为'tbo_sk'的复选框和名为'nilaiblksk'的textField p>
&lt;?php echo $ form-&gt; checkBox($ model,'tbo_sk'); ?&gt; &lt; div style =“display:none”&gt;&lt;?php echo $ form-&gt; textField($ model,'nilaiblksk'); ?&gt;&lt; / div&gt; code> pre>
我的问题是,我们如何在showHide.js文件中生成javascript代码,每当我检查时都会显示textField checkBox,否则如果未选中则隐藏textField? p>
在我的div标签中,我使用style =“display:none”来隐藏textField。 p>
提前致谢! p> div>
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