CakePHP:show/hide 基于复选框状态的表单控件

CakePHP: show/hide form control based on checkbox status

我在 cakephp 表单中有这 3 个控件:

echo $this->Form->control('recurring', ['empty' => true]);
echo $this->Form->control('recurring_months', ['options' => $months, 'empty' => true]);
echo $this->Form->control('recurring_start_date', ['empty' => true]);

如果未选中字段 recurring,我希望隐藏字段 recurring_monthsrecurring_start_date - 正确。

所以我尝试使用这个 javascript 代码,但没有用。我该如何解决?

<script>
    //hide recurring options if its not recurring
    $(document).ready(function() {  
        $('#recurring').on('change', function(e){ 
            if($(this).is(':checked')) { 
                $('#recurring_months').show();
                $('#recurring_start_date').show();
            }
            else{ 
                $('#recurring_months').hide();
                $('#recurring_start_date').hide();
            }
        });
    });
</script>

这样的事情怎么样,将输入包装在 div 中并隐藏它而不是单独隐藏字段:

echo $this->Form->control('recurring', ['empty' => true]);
echo $this->Html->tag('div',
    $this->Form->control('recurring_months', ['options' => $months, 'empty' => true]) .
    $this->Form->control('recurring_start_date', ['empty' => true]),
    ['id' => 'recurring_fields']
);

<script>
    //hide recurring options if its not recurring
    $(document).ready(function() {  
        $('#recurring').on('change', function(e){ 
            if($(this).is(':checked')) { 
                $('#recurring_fields').show();
            }
            else{ 
                $('#recurring_fields').hide();
            }
        });
    });
</script>