Welcome Guest, Not a member yet? Register   Sign In
Populating a dropdown based on the values selected on the first dropdown
#1

[eluser]Delvin[/eluser]
Hello there,

From the controller file I am passing a 2 dimensional array of student names and their respective class to the view file
Code:
$query = $this->db->query('SELECT Class_ID, First_Name, Middle_Name, Last_Name FROM student ORDER BY Class_ID');
                $names = array(); // Declare an empty arry to recieve data in the loop

                foreach ($query->result_array() as $row){
                    $temp = $row['Class_ID'];
                    $temp1 = $row['First_Name'].$row['Middle_Name'].$row['Last_Name'];

                    $names[] = array(
                        'Class_name' => $temp,
                        'Std_name'   => $temp1
                    );
                }
                $data['names'] = $names;
                $this->load->view('m_student/classlist_stdview.php',$data);

In the view file I have populated the first select box with the unique class name:
Code:
Select Class <select name="listclass" id="list_class">
    <option> </option>
    &lt;?php
        foreach ($names as $class => $student){
            if ($student['Class_name'] == $temp)    //To have only unique class names updated.
                continue;
            $temp = $student['Class_name'];    
            echo "<option>".$student['Class_name']."</option>";
        }
    ?&gt;
    </select>

Now as I select each class on the first dropdown, i want the second drop down to display the respective sutdent name. The student name is already available on the array that was passed to this view file.

I know I can do this by calling a JS function on the 'onchange' event of select, but am stuck on how will I pass this array to JS, so that JS can populate the second drop down.
Could some help me on how could I do this or please help if there is an easier way of doing this.


Delvin
#2

[eluser]gigas10[/eluser]
I normally just call a JS function in the onChange event handler. I pass in this.value in the function parameters. From the JS function, I would then call a php function and again pass in the value that was passed into the JS function. From my php function, I would gather the required data from the table and return it to the JS function in the form of a string containing all the options that would be in the dropdown. From here my JS function would load the div on the page using AJAX and output the returned string from the php function. PM me if you want examples of my code. It's a little messy and I am sure there are other ways of doing this, but this is how I always go about creating my cascading dropdown menus.




Theme © iAndrew 2016 - Forum software by © MyBB