Reputation: 2949
I'm new to JQuery, I'm using PHP in my code. I don't know how to make a dynamic dropdown. When user chooses from the first dropdown - region, next he to choose from onother dropdown - school, which is in this region. Please help! My code is:
<html>
<head>
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<script type="text/javascript">
</script>
</head>
<body>
<?php
echo form_open();
echo "<table border = '0' >";
echo "<tr><td> Region:* </td><td>";
echo "<select name = 'region[]' id='region' >";
foreach($regions as $row)
{
echo '<option value= "'.$row->region.'">'.$row->region.'</option>';
}
echo "</select>";
echo "</td></tr>";
echo "<tr><td> School:* </td><td>";
echo "<select name = 'school[]' id='school'>";
foreach($school_show as $row)
{
echo '<option value="'.$row->school_name.'">'.$row->school_name.'</option>";
}
echo "</select>";
echo "</td></tr>";
echo form_submit($data);
echo "</form>";
echo "</table>";
Controller is:
<?php
class Home extends CI_Controller {
public function register()
{
$this->load->model('user_model');
$data['dynamic_view'] = 'register_form';
$data['regions'] = $this->user_model->regions_show();
$data['school_show'] = $this->user_model->school_show();
$this->load->view('templates/main',$data);
}
}
Model is:
<?php
class User_model extends CI_Model {
public function __construct() {
parent:: __construct();
$this->load->database();
$this->load->helper('array');
}
public function regions_show() {
$this->db->select('region');
$this->db->distinct('region');
$this->db->from('schools');
$result=$this->db->get();
return $result->result();
}
public function school_show() {
$this->db->select('school_name');
$this->db->from('schools');
$result=$this->db->get();
return $result->result();
}
}
Upvotes: 0
Views: 116
Reputation: 522
Use a java-script function with the first drop-down's onChange property. So, when the first drop-down value is selected it will call and pass the value to the function which will then be used to populate the second drop-down.
A simple example of the idea can be as follows -
function populateSecond(id)
{
if(id == 1){
$('select[name=first]').append('<option value="a">A</option>');
}else{
$('select[name=first]').append('<option value="b">B</option>');
}
}
<select name="first" onChange="populateSecond(this.value);">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<select name="second">
</select>
Upvotes: 1