2016-04-20 21 views
6

私はドロップダウンリストでonclickを使用しようとしています。Yii2 Jquery onchangeドロップダウン

これが私の見解です:

<?= $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:私は初心者です。

+2

使用しているコードが機能名と異なる場合は、 'onchange'は' getSalutationValue'で、関数は 'getSolutationValue'です。 – Alex

答えて

3

私はそれを解決しました。問題は値を宣言していないことと、on.changeを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') ?> 

$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"); 
} 
}); 
1

このコードを試してください。

$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') ?> 
+0

あなたの答えをありがとう。しかし、私はこのエラー "Uncaught ReferenceError:getSalutationValueは定義されていません"と何も起こりませんでした。 –

+1

あなたは '' onchange '=>' getSalutationValue''をdropdownlistのオプションとして持っていますので、そこから削除してください。 – GAMITG

関連する問題