jeanc
jeanc

Reputation: 4833

Yii dropdownlist depending on two dropdownlists

I have seen this wiki where they populate a dropdownlist of cities, depending of the value of another dropdownlists that contains countries, using an ajax call with the update option. I need to implement something similar, but my dropdownlist depends on two dropdownlists:

<div class="row">
    <?php echo CHtml::label('Countries', 'country_id'); ?>
    <?php echo CHtml::dropdownlist('country_id', '',$countries); ?>
</div>

<div class="row">
    <?php echo $form->labelEx($model,'globaladmin'); ?>
    <?php echo $form->dropDownList($model,'globaladmin',User::itemAlias('AdminStatus')); ?>
    <?php echo $form->error($model,'globaladmin'); ?>
</div>

The user must select a country, and then only if in the second list "No" is selected, a new dropdown lists must be populated with the cities info (just like in the wiki example).

As I said it is similar to the example, but the new dropdown depends on 2 values (the id of the contry selected on the first list and if "No" is selected in the second one). How could I solve it?

EDIT: Explaining a little more

In the example, the country dropdown which contains the ajax call is like:

echo CHtml::dropDownList('country_id','', array(1=>'USA',2=>'France',3=>'Japan'),
array(
'ajax' => array(
'type'=>'POST', //request type
'url'=>CController::createUrl('currentController/dynamiccities'), //url to call.
'update'=>'#city_id', //selector to update
))); 

I can't define such a ajax call in my country list, because I must wait the value of the second dropbox. Only if "No" is selected in this list, the ajax will be executed (and the city dropdownlist populated and showed). If "Yes" is selected then the city dropdownlist must be hidden.

Upvotes: 0

Views: 1790

Answers (1)

Ali MasudianPour
Ali MasudianPour

Reputation: 14459

Just add an ID to your globaladmin drop down and then do like below:

$("#THE ID YOU HAVE SET").on('change',function(){
    // You can use $(this).val()
    // and send it via an ajax request into your own url
    var valueOfMyGlobalAdminDropDown=$(this).val();
    if(valueOfMyGlobalAdminDropDown=="yes"){
       //DO SOMETHING
    }else{
       //DO SOMETHING ELSE
    }
});

it is also strongly recommended to use jquery live(in jquery version -1.7) or jquery ON(in jquery version +1.7) to keep your page alive in ajax requests.

Upvotes: 2

Related Questions