Yii2 Jquery onchange下拉列表


Yii2 Jquery onchange dropdown

我正试图在下拉列表上使用onclick。

这是我的观点:

<?= $form->field($model, "contact_gender")->dropDownList(ArrayHelper::map($genders, 'value', 'description'),['class'=>'form-control','prompt'=>'Please Select','onchange'=>'getSalutationValue','required'=>true])->label('Gender') ?>
<?= $form->field($model, "contact_title")->dropDownList(ArrayHelper::map($salutations, 'value', 'description'),['class'=>'form-control Salutation','prompt'=>'Please Select','required'=>true])->label('Salutation') ?>

这就是我的功能:

<script>
function getSolutationValue() {
    var value = (this.value); 
    if(value == 'Male'){
        $('.Salutation').val('0');
    }
    if(value == 'Female'){
        $('.Salutation').val('1');
    }
    if(value == 'Unspecified'){
        $('.Salutation').val('2');
    }
}
</script>

我想要的是,当我从contact_gender中选择一个值时,会在contact_title中自动选择一个数值。提前谢谢。

p/s:我是个新手。

我解决了它。问题是我没有声明值,我添加了两次on.change。这是正确的代码。感谢您的回复。

<?= $form->field($model, "contact_gender")->dropDownList(ArrayHelper::map($genders, 'value', 'description'),['class'=>'form-control gender','prompt'=>'Please Select','required'=>true])->label('Gender') ?>
<?= $form->field($model, "contact_title")->dropDownList(ArrayHelper::map($salutations, 'value', 'description'),['class'=>'form-control Salutation','prompt'=>'Please Select','required'=>true])->label('Salutation') ?>
$this->registerJs('
 $(".gender").change(function(){
    var value = this.value;
    if(value == "MALE"){
    $(".Salutation").val("0");
    }
    if(value == "FEMALE"){
    $(".Salutation").val("4");
    }
    if(value == "UNSPECIFIED"){
    $(".Salutation").val("23");
 }
});

您应该试试这段代码。

$this->registerJs("
$(function(){
   $('.gender').change(function(){
        getSalutationValue(this.value); 
    });
   function getSalutationValue(value) {
      if(value == 'Male'){
        $('.Salutation').val('0');
      }
      if(value == 'Female'){
        $('.Salutation').val('1');
      }
      if(value == 'Unspecified'){
        $('.Salutation').val('2');
      }
  }
  });
");
<?= $form->field($model, "contact_gender")->dropDownList(ArrayHelper::map($genders, 'value', 'description'), ['class'=>'form-control gender','prompt'=>'Please Select', 'required'=>true])->label('Gender') ?>
<?= $form->field($model, "contact_title")->dropDownList(ArrayHelper::map($salutations, 'value', 'description'),['class'=>'form-control Salutation','prompt'=>'Please Select','required'=>true])->label('Salutation') ?>