简体   繁体   English

Yii2:如何使用jQuery删除必需的属性

[英]Yii2: How to remove required attribute with jQuery

I have a textInput field that is required but when the checkbox is pressed the field is not require. 我有一个textInput 字段 ,它是必需的,但是当按下复选框时,该字段不是必需的。

<div class="checkbox">
    <label>
        <?= Html::checkbox('myCheckbox', false, ['id' => 'myCheckbox']) ?>
        I don't send my address
    </label>
</div>

<?= $form->field($model, 'address')->textInput(['class' => 'form-control', 'id' => 'address']) ?>

I need to remove the required attribute when the user checks the checkbox. 当用户选中复选框时,我需要删除必填属性。 I think jQuery is the best approach so I tried this but it doesn't work: 我认为jQuery是最好的方法,所以我尝试了一下,但它不起作用:

$("#myCheckbox").change(function() {
    if (this.checked) {
        $("#address").prop("required", "false");
    }
    else {
        $("#address").prop("required", "true");
    }
});

I can see that the required attribute is not on the input tag, it is in his parent tag: 我可以看到required属性不在输入标签上,而是在其父标签中:

<div class="form-group field-address required has-success">
    <label class="control-label" for="address">Address</label>
    <input type="text" id="address" class="form-control" name="Form[address]" aria-required="true" aria-invalid="false">

    <div class="help-block"></div>
</div>

Why are you not using when and whenClient options? 为什么不使用whenwhenClient选项? change the checkbox to a model field, declare a public property with the name myCheckbox 将复选框更改为模型字段,并声明名称为myCheckbox的公共属性

public $myCheckbox

inside the Form Model then change the following. Form模型中,然后更改以下内容。

<div class="checkbox">
    <label>
        <?= Html::checkbox('myCheckbox', false, ['id' => 'myCheckbox']) ?>
        I don't send my address
    </label>
</div>

to

<div class="checkbox">
    <label>
        <?= $form->field($model,'myCheckbox')->checkbox(['uncheck'=>null,'id'=>'myCheckbox']) ?>
        I don't send my address
    </label>
</div>

then inside your rules in the Form Model do the following 然后在Form模型的规则内执行以下操作

['address' , 'required' , 'when' => function($model) {
                    return ($model->myCheckbox!==null);
                } , 'whenClient' => 'function(attribute,value){return ($("#myCheckbox:checked").length>0)}' ] ,

Hope it helps you out 希望它可以帮助您

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM