EllisLab text mark
Advanced Search
     
Populate dropdown based on another dropdown selection using jquery
Posted: 14 June 2011 06:19 PM
Avatar
Joined: 2011-06-02
10 posts

Hi all, I have a dropdown with providers and one with products. I want when I select a provider to have the second drop down with products from the selected provider.
Can anyone help me to populate the second dropdown ?

my view is:

<html>

        <
head>
                
                <
style type="text/css">
                        
select {
                                background
-color#134553;
                                
color#ffffff;
                                
width200px;
                                
positionrelative;
                                
margin0 auto;
                                
top50px;
                                
font-size24px;
                        
}
                
</style>
                
[removed]config->item('base_url');?>lib/jquery-1.6.1.min-dev.js">[removed]
                 [removed]

                        function refresh_products(){
                                var selected_provider = $('#providers option:selected').val();
                                $('#products').load("
/test/dropdown/getproducts/777".replace("777", selected_provider));
                                alert(selected_provider);
                        }

                        $(document).ready(function(){
                                $('#providers').change(refresh_products);
                        });

                [removed]
        </head>


        <body>
                <h1> testing jquery dropdown in cascade</h1>

                <input type="
text" id="debug">Debug text</input><br></br>

                <select id="
providers" name="providers">
                <?php if(isset(
$providers)) : foreach($providers as $provider) : ?>
                        <option value=<?php echo 
$provider->id; ?>>
                                <?php echo 
$provider->name; ?>
                        </option>                        
                <?php endforeach; endif; ?>
                </select>

                <select id="
products" name="products">
                </select>
        </body>


</html> 

and the controller:

class Dropdown extends CI_Controller
{

    
function index()
    
{
        
//check session
                
$this->load->library('Mysession');
                if (
$this->mysession->isInactive($this)) return;

                
$this->load->model('crud2_model');

                if(
$query2 $this->crud2_model->select_all('select p.id, p.name from expenses_providers p order by p.name asc'))
                
{
                        $data[
'providers'$query2;
                
}
                
else
                
{
                        $data[
'providers'= array();
                
}
                

                
        $this
->load->view('test/dropdown'$data);
    
}
        
        
function getproducts()
    
{
        
//check session
                
$this->load->library('Mysession');
                if (
$this->mysession->isInactive($this)) return;

                
$this->load->model('crud2_model');

                if(
$query2 $this->crud2_model->select_all('select p.id, p.name from expenses_products p where p.providerid = '.$this->uri->segment(4).' order by p.name asc'))
                
{
                        $data[
'products'$query2;
                
}
                
else
                
{
                        $data[
'products'= array();
                
}
                $results 
$query2->result();
                
$returnValue "";
                foreach(
$results as $result)
                
{
                        $returnValue 
$returnValue."<option value=".$result->id.">".$result->name."</option>";
                
}
                
return $returnValue;
    
}
    

The alert screen shows the correct selected value…
What happens is that when I select anything in the first drop down the second is populated with extremely many empty records. I am to tired to figure this one out so any help is appreciated. Thank you!

 
Posted: 15 June 2011 10:52 AM   [ # 1 ]   [ Rating: 0 ]
Avatar
Joined: 2010-12-20
1591 posts

Did you check the returned data from your controller?

 Signature 

“In Code We Trust.”


CI Library : Gas ORM | Proxy

 
Posted: 15 June 2011 05:17 PM   [ # 2 ]   [ Rating: 0 ]
Avatar
Joined: 2011-06-02
10 posts

You are perfectly right, thank you! I resolved my issue today and I wanted to post the solution here, anyway, for others. It seems that a rested brain is a lot better than a sleepy one. So here is the solution that works (it is just a simple example)

Controller:

function index()
    
{
        
//check session
                
$this->load->library('Mysession');
                if (
$this->mysession->isInactive($this)) return;

                
$this->load->model('crud2_model');

                if(
$query2 $this->crud2_model->select_all('select p.id, p.name from expenses_providers p order by p.name asc'))
                
{
                        $data[
'providers'$query2;
                
}
                
else
                
{
                        $data[
'providers'= array();
                
}
                

                
        $this
->load->view('test/dropdown'$data);
    
}
        
        
function getproducts()
    
{
        
//check session
                //$this->load->library('Mysession');
                //if ($this->mysession->isInactive($this)) return;
                
                
 
                
$this->load->model('crud_model');

                
$query2 $this->crud_model->select_all_for_parentid('expenses_products''providerid'$this->uri->segment(4));
                
                
                
                foreach(
$query2 as $result)
                
{
                        
echo "<option value=".$result->id.">".$result->name."</option>";
                
}
                
    } 


Then the view looks like this

[removed]

                        
function refresh_products(){
                                
var selected_provider = $('#providers option:selected').val();
                                     
                                $(
'#products').load("/test/dropdown/getproducts/"+selected_provider);
                                
                        
}

                        
$(document).ready(function(){
                                refresh_products
();
                                $(
'#providers').change(refresh_products);
                        
});

                
[removed]
        
</head>


        <
body>
                <
h1testing jquery dropdown in cascade</h1>

                <
input type="text" id="debug">Debug text</input><br></br>

                <
select id="providers" name="providers">
                
<?php if(isset($providers)) : foreach($providers as $provider) : ?>
                        
<option value=<?php echo $provider->id?>>
                                
<?php echo $provider->name?>
                        
</option>                        
                
<?php endforeach; endif; ?>
                
</select>

                <
select id="products" name="products">
                </
select>
        </
body

I hope this helps someone!

All the best!

Marius

 
Posted: 26 October 2011 09:53 AM   [ # 3 ]   [ Rating: 0 ]
Joined: 2011-10-26
1 posts

i am a newb to codeignitor and i am trying to setup the same form.
Could u kindly also post the code for your model and full js.

 
Posted: 01 November 2011 04:29 PM   [ # 4 ]   [ Rating: 0 ]
Avatar
Joined: 2011-06-02
10 posts

unfortunatelly I don’t have that code anymore.
for JS i just use what is above and I make a reference to JQuery. Unforuntatelly i cannot copy/paste it here because the validator here, on this forum, will filter out the paths that I use.

In terms of model, you need to have 2 different queries, one bringing parents and second that brings children for a specific parent id

an example for that is:

function select_all_for_parentid($table_name$parentid_field$id)
        
{
                
//$this->db->where($parentid_field, $this->uri->segment(4));
                
$this->db->where($parentid_field$id);
                
$query $this->db->get($table_name);
                
                
                return 
$query->result();
        

Let me know if that is enough for you to move on. I will be on vacation for this week and I will be back next week (if I will recover after Florida Ford Ironman I have this Saturday). Good luck!

 
Posted: 15 December 2011 06:23 PM   [ # 5 ]   [ Rating: 0 ]
Joined: 2010-01-08
95 posts

moriokasan,

I have taken your example and gotten it to work on my state/city drop downs. I do not know JQuery but I have been trying to modify your script to show a temporary “Retrieving…” message after state selection and than the city list when the data is ready. However, I have only been able to accomplish showing the “Retrieving…” text when a value is selected, no drop down appears.

Below is the version that works.

[removed]
function refresh_cities()
{       
 
var selected_region = $(\'#region option:selected\').val();
 $(
\'#cities\').load("/util/dropdown/getcities/"+selected_region);
}
    
$(document).ready(function(){
 refresh_cities
();
 $(
\'#region\').change(refresh_cities);
});
[removed] 

Below is my modified version that is not performing as desired.

[removed]
function refresh_cities()
{       
 
var selected_region = $(\'#region option:selected\').val();
 $(
"#region").change( function()
 
{
  
$("#result").html(\'Retrieving ...\');
  $(
\'#cities\').load("/util/dropdown/getcities/"+selected_region);
 
});
}
    
$(document).ready(function(){
                                 
$("#cities").hide();
 
refresh_cities();
 $(
\'#region\').change(refresh_cities);
});
[removed] 

Any help is appreciated.

 
Posted: 15 December 2011 08:59 PM   [ # 6 ]   [ Rating: 0 ]
Joined: 2010-01-08
95 posts

I figured it out by combining this script and another.

[removed]
          $(document).ready(function(){
              $(”#cities”).hide();
           
              $(”#region”).change( function() {
                $(”#cities”).hide();
                $(”#result”).html(‘Retrieving ...’);
                $.ajax({
                  type: “POST”,
                  data: “data=” + $(this).val(),
                  url: “/util/dropdown/getcities/”+$(this).val(),
                  success: function(msg){
                      if (msg != ‘’){
                        $(”#cities”).html(msg).show();
                        $(”#result”).html(’‘);
                      }
                      else{
                        $(”#result”).html(’No item result’);
                      }
                  }
                });
              });
          });
          [removed]

 
Posted: 20 December 2011 06:07 PM   [ # 7 ]   [ Rating: 0 ]
Avatar
Joined: 2011-06-02
10 posts

That’s a good question! Unfortunately I don’t know the answer now. When we find out about it we should post it here.

 
Posted: 20 December 2011 08:10 PM   [ # 8 ]   [ Rating: 0 ]
Joined: 2010-01-08
95 posts

moriokasan, I resolved the issue with a work around. I posted the fix already. Thanks.