Yii2 输入字段设置禁用取决于其他字段


Yii2 inputfield set disabled depend other field

我有一个创建表单,我问两件事。第一个是user_id另一个是名称。

我想实现这一点,如果设置了第一个字段,那么另一个字段将被禁用。如果因为我想保存该特定用户的名称。我用javascript试过了,但我对js很菜鸟,这就是为什么问你。

我的代码是:

    $script = <<<JS
        $('#contact-user_id').on('afterValidate', function (e) {
            if ( $('#contact-user_id').value.length > 0 ) {
                return document.getElementById("contact-name").disabled = true;
            }
        });
    JS;
    $this->registerJs($script);
    ?>

        <div class="row">
            <div class="col-md-6">
                <?= $form->field($model, 'user_id')->widget(Select2::className(), [
                    'value' => $model->user_id,
                    'data'=>ArrayHelper::map(User::find()->all(), 'user_id', 'name'),
                    'options'=>['placeholder'=>'Select User...'],
                    'pluginOptions' => [
                        'allowClear' => true
                    ],
                ]) ?>
                <?= $form->field($model, 'name')->textInput(['maxlength' => true]) ?>
                <?= $form->field($model, 'email')->textInput(['maxlength' => true]) ?>
...

首先,将脚本添加到视图底部或将其添加到$(document).ready();

现在,根据字段更改名称字段的代码user_id。

$('#contact-user_id').change(function(){
    if ($(this).val() != 0 || $(this).val() != '') {
       $('#contact-name').attr('disabled',true);
    }
});