[eluser]Bigil Michael[/eluser]
how can i create dynamic dropdownbox using ajax. That means there are 2 dropdown boxes. items in the 2nd dropdown box depends on the selection of the 1st drop down box.
model
class Home_model extends Model {
function Home_model(){
parent::Model();
}
function select_category()
{
$result_category = $this->db->query(“SELECT category_id,category_name FROM car_category”);
return $result_category->result();
}
function select_car($id)
{
$result_category = $this->db->query(“SELECT id,car_name FROM cars WHERE category_id=’$id’”);
return $result_category->result();
}
}
controller
class Home extends Controller {
var $data = array();
function Home(){
parent::Controller();
$this->load->helper(array(‘form’));
$this->load->model(‘Home_model’);
$this->load->library(array(‘form_validation’));
$this->load->library(‘ajax’);
}
function index($id=’‘)
{
$this->data[‘carcategory’] = $this->Home_model->select_category();
$id = $this->input->post(‘car_group_id’);
$this->data[‘car’] = $this->Home_model->select_car($id);
$this->load->view(‘home’,$this->data);
}
}
view
<select name=“car_group” class=“list_1” id=“car_group” >
<?php
foreach($carcategory as $row)
{
?>
<option value=”<?php echo $row->category_id?>” <?php echo set_select(‘car_group’,$row->category_id);?> ><?php echo $row->category_name?></option>
<?php
}
?>
</select>
second dropdown
<select name=“cars_id” class=“list_1” id=“cars_id”>
<?php
foreach($car as $row)
{
?>
<option value=”<?php echo $row->id?>” <?php echo set_select(‘cars_id’,$row->id);?> ><?php echo $row->car_name?></option>
<?php
}
?>
</select>
javascript
$(‘car_group’).change(function () {
var id = $(‘car_group option
elected’).attr(‘value’);
$.post(”<?php echo base_url();?>/home/index”, {car_group_id: id}, function (data) {
if (data) {
$(‘cars_id’).html(data);
$(‘cars_id’).show();
}
});
});