jqueryyii2active-form

Yii2 - dropDownList to populate textInput


I have this View:

<div class="col-xs-12 col-sm-12 col-lg-12">
   <?= $form->field($model, 'name')->dropDownList(['E' => 'Data Entry', 'S' => 'Mark Entry'], ['prompt' => 'Select Option']) ?>
</div>

<div class="col-xs-12 col-sm-12 col-lg-12">
   <?= $form->field($model, 'detail')->textInput(['maxlength' => 20, 'placeholder' => $model->getAttributeLabel('detail')]) ?>
</div>

What I want to achieve is that when I click on the dropDownList, If the value is Data Entry then the textInput will be Data Entry. Then if the value is Mark Entry, then the textInput will be Mark Entry.

How do I achieve this?


Solution

  • You can set id attribute for each input to get their values by jQuery:

    <div class="col-xs-12 col-sm-12 col-lg-12">
        <?= $form->field($model, 'name')->dropDownList(['E' => 'Data Entry', 'S' => 'Mark Entry'], ['id' => 'firstInput', prompt'=>'Select Option']) ?>
    </div>
    
    <div class="col-xs-12 col-sm-12 col-lg-12">
        <?= $form->field($model, 'detail')->textInput(['id' => 'secondInput', maxlength' => 20, 'placeholder' => $model->getAttributeLabel('detail')]) ?>
    </div>
    

    And your jQuery code:

    $('#firstInput').change(function() {
       var firstInputValue = $(this).val();
       $('#secondInput').val(firstInputValue);
    });