php - Get selected value from CHtml::dropDownList


I have a question about Yii framework.

Let's say I have dropdown list like the code listed below.

I need to print selected value and I try to do it with$_POST['countries'] but nothing happened.

I just need the selected value to store in a variable so I can manipulate it.

      echo CHtml::dropDownList('countries', $select = array(),
      CHtml::listData($countries, 'code', 'name'));



The$_POST var is corresponding to some data sent usingHTTP protocol, so to use this var the client (the browser) need to send data to the server.

Since you want to display something just after the user selected a value in the dropdown list, you'll need to use javascript which is executed on the client side.

Here's an example that will get the selected value using jquery. You should then update the div where you want the value to appear, but since it's not in your question I can't help!

    var value = $('#dropDownId :selected').text();
    //Here update the div where you need to see the selected value

WheredropDownId is the id that you need to give to your dropDownList (in the CHtml::dropDownList html options)




You can also use an Ajax request. Its even better if you want to make some dependent dropdown lists. For example:

echo $form->dropDownList($profile, $field->varname,CHtml::listData(Countries::model()->findAll(),'short','title'), array(
    'empty'=>"Select country",  
    'ajax' => array(
                    'type' => 'POST',
                    'update' => '#Profile_state',                        
                    'success'=> 'function(data) {

                                            } ',


Then in your controller you can use POST Example:

    public function actionState()

                  array(':country_code'=> $_POST['country']));                
 echo "<option value=''>Select state</option>";
            foreach($data as $value=>$state)  {
                        echo CHtml::tag
                                ('option', array('value'=>$value),CHtml::encode($state),true);


People are also looking for solutions to the problem: php - Remove duplicates in foreach loop from custom taxonomy


Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.