2016-03-04 199 views
0

我有一個創建表單,在這裏我問兩件事情。 第一個是user_id,另一個是名字。Yii2輸入字段設置禁用取決於其他字段

我想實現這一點,如果第一個設置,那麼其他字段將被禁用。 如果因爲我想保存特定用戶的名字。 我試過用javascript,但即時通訊與js noob,這就是爲什麼問你。

我的代碼是:

$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]) ?> 
... 

回答

1

首先,在您的視圖底部添加腳本或將其添加到$(document).ready();

現在,代碼依賴於更改名稱字段user_id字段。

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

謝謝你的工作。 – user2241077

+0

隨時buddy :) –