如何使用jquery进行动态下拉列表

时间:2015-04-02 09:49:21

标签: php jquery

我是JQuery的新手,我在代码中使用PHP。我不知道如何进行动态下拉菜单。当用户从第一个下拉区域选择时,接下来他可以选择另一个下拉列表 - 学校,这是在该地区。请帮忙! 我的代码是:

<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>";

控制器是:

<?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);
            }   
}

模型是:

<?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();

    }
}

1 个答案:

答案 0 :(得分:1)

将java脚本函数与第一个下拉列表的onChange属性一起使用。因此,当选择第一个下拉值时,它将调用并将值传递给函数,然后该函数将用于填充第二个下拉列表。

这个想法的一个简单例子如下 -

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>