我想在我选中或取消选中复选框时提交搜索表单。我有以下代码,但无法使其正常工作……我想这很简单,但无法解决!
<?= $form->field($searchModel, 'pets_allowed')->checkbox(['options'=>['onchange'=>'"this.form.submit();}"']]); ?>
预先感谢:)
答案 0 :(得分:0)
从表达式"
和'"this.form.submit();}"'
中删除双引号}
。然后,您需要传递选项数组而不是关键字options
,请参阅checkbox的API文档
所以应该是
<?= $form->field($searchModel, 'pets_allowed')->checkbox(['onchange' => 'this.form.submit()']); ?>
但是上面脚本中的问题是,即使您取消选中它,也将提交表单,所以更好的方法应该是选中复选框的状态。我将使用jquery和heredoc,如下所示,这样您可以在代码中具有可读性并易于编辑。
<?php
use yii\widgets\ActiveForm;
$js = <<<JS
$("#pets_allowed").on('change',function(){
// to submit only if the checkbox is checked otherwise
// you can remove the check and just use the submit statement
if($(this).is(':checked')){
$(this).closest('form').submit();
}
});
JS;
$this->registerJs($js, \yii\web\View::POS_READY);
?>
<?php $form = ActiveForm::begin();?>
<?= $form->field($searchModel, 'pets_allowed')->checkbox(['id'=>'pets_allowed']); ?>
<?php ActiveForm::end();?>