繁体   English   中英

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中自动选择一个值。 提前致谢。

ps:我是新手。

我解决了 问题是我没有声明值,而是两次添加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') ?>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM