NoBody NoBody - 5 months ago 425
PHP Question

Yii2 - Dropdownlist is selected and set value for input field

I have this in my view (_form.php).

<div>
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#pilih_dulu").change(function(){
$(this).find("option:selected").each(function(){
if($(this).attr("value")=="1"){
$(".box").not(".1").hide();
$(".1").show();
}

else if($(this).attr("value")=="2"){
$(".box").not(".2").hide();
$(".2").show();
}

else if($(this).attr("value")=="3"){
$(".box").not(".3").hide();
$(".3").show();
}

else{
$(".box").hide();
}
});
}).change();
});
</script>
</div>

<div class = "col-lg-4">
<?= $form->field($model, 'kat_id')->label(true)->dropDownList(
ArrayHelper::map(TblKategori::find()->all(),'kat_id','kat_kategori'), ['id' => 'pilih_dulu']
) ?>
</div>

<div class="1 box col-lg-4">
<?= $form->field($model, 'sok_id')->textInput(['value' => 1]) ?>
</div>

<div class="2 box col-lg-4">
<?= $form->field($model, 'sok_id')->textInput(['value' => 2]) ?>
</div>

<div class="3 box col-lg-4">
<?= $form->field($model, 'sok_id')->textInput(['value' => 2]) ?>
</div>


The problem is its not store the correct value. Its seems like it always store value in the last box.

Its suppose to work like this :


  1. if value 1 is selected from dropdownlist, it should store value for sok_id in "1 box".

  2. if value 2 is selected from dropdownlist, it should store value for sok_id in "2 box".

  3. if value 3 is selected from dropdownlist, it should store value for sok_id in "3 box".



please help me. thank you

Answer

If I figured out correctly you can do this, in simple way:

<div class = "col-lg-4">
   <?= $form->field($model, 'kat_id')->label(true)->dropDownList(
      ArrayHelper::map(TblKategori::find()->all(),'kat_id','kat_kategori'), ['id' => 'pilih_dulu', 'onchange' => 'if($(this).val() == 1) {
                        $("#'.Html::getInputId($model, 'sok_id').'").val($(this).val());
                    }
                    else if($(this).val() == 2) {
                        $("#'.Html::getInputId($model, 'sok_id').'").val($(this).val());
                    } else if($(this).val() == 3){
                        $("#'.Html::getInputId($model, 'sok_id').'").val($(this).val());
                    }'
   ']) ?>
</div>

 <div class="box col-lg-4">
    <?= $form->field($model, 'sok_id')->textInput() ?>
</div>

No need for 3 fields and yes add show() and hide() method where necessary.