在改变form_dropdown codeigniter

时间:2013-02-04 07:35:22

标签: php codeigniter

我正在使用codeigniter中的form_dropdown()。

我有表countrystate(id,countryname,statename)

我填写了countryname&填写form_dropdown('fd_country')。

现在我想根据所选的国家/地区名称显示州名。请帮忙。

1 个答案:

答案 0 :(得分:3)

就像我做的那样 http://help.webhostel.org/h14682223

控制器代码

public function index() {
        $this->load->database();
        $this->db->select('countryname');
        $this->db->group_by('countryname');
        $query = $this->db->get('country');

        foreach($query->result() as $item)
            $countries[$item->countryname] = $item->countryname;

        $data = array('department' => $countries);

        $this->load->helper('form');
        $this->load->view('welcome_message', $data);
}

public function get_subdepartment() {
    $this->load->database();
    $this->load->helper('form');
    $states = array();  
    if($this->input->post('dep_selected')) {
        $this->db->select('countrystate');
        $this->db->where(array('countryname' => $this->input->post('dep_selected')));
        $query = $this->db->get('country');

        foreach($query->result() as $item)
            $states[$item->countrystate] = $item->countrystate;
    }

    $output = form_dropdown('subdept', $states);
    echo $output;
}

模板部分

<script type="text/javascript">
function get_subdepartment() {
    var dep_selected = $('select[name=txtDept]').val();
    $.ajax({
        data: {
            dep_selected: dep_selected,
        },
        type: 'POST',
        url: '/welcome/get_subdepartment',
        success: function(data){
            console.log(data);
            $('.subdepartment').html(data);
        }
    })
}
</script>
<div id="container">
<h1>Welcome to CodeIgniter</h1>
<div id="body">
<? echo form_open("addEmployee"); $newEmp = array('name' => 'newEmployee', 'id' => 'newEmployee', 'value' => set_value('ne')); ?>
    <div for='newEmp'><input type="text" name="txtEmpName" id="txtEmpName" maxlength="25" /></div> 
    <div for='newEmp'>
        <? echo form_dropdown($name = 'txtDept',$Options = $department, array($this->input->post('txtDept')),'onChange="get_subdepartment()"'); ?>
    </div>
    <div for='newEmp' class="subdepartment"></div>
<? echo form_submit('do_submit', 'Submit'); ?>
<? echo form_close(); ?>
</div>