同一表

时间:2017-03-21 21:23:07

标签: javascript jquery json ajax codeigniter

我有一个名为“drivers”的表,其中包含3个字段“id”,“name”和“mob”。

我有2个下拉菜单。

  • 第一个下拉列表:想要显示驱动程序的名称表单数据库
  • 第二个下拉列表:想要显示在第一个下拉列表中选择的驱动程序。

请查看我现有的代码并尝试解决我的问题。 这是我的代码:

抱歉由于堆栈溢出错误,我无法在此处粘贴代码。我在此链接上粘贴了代码:here

3 个答案:

答案 0 :(得分:1)

您需要在驱动程序选择框中使用由更改功能启动的ajax。它应该是这样的:

<select onchange="getval(this.value)">
<option value="1">One</option>
<option value="2">Two</option>
</select>

在您的方案中应该是:

<select name="dname" class="form-control" onchange="getval(this.value)">
// <?php

foreach($results_drivers as $row)
{ 
 echo '<option value="'.$row->id.'">'.$row->name.'</option>';

}
?>
</select>

然后编写一个jquery函数:

function getval(driverid){
     $.ajax({url: "controller/newmethod/"+driverid, success: function(result){
    //now populate the mobile number in the select box. 
}});
}

在您的控制器中:

Public function newmethod($id){
$driver_data = //query to get data from your table with where cluase
/// where id = $id
//and then get the data in format you like, let say array 
print_r($driver_data);exit;
}

Now in jquery , you have data of driver in result variable that is passed as a parameter in function . now that should be easy for you . if you still have question or problem implementing it , let me know. It is easy task and you are going to use it in future a lot of times. Thats why I want you to do it your self and just telling you the methodology. 

答案 1 :(得分:1)

//你也可以使用id和jquery功能

 <select name="dname" class="form-control" id="selectid">
    foreach($results_drivers as $row)
     {
      echo '<option value="'.$row->id.'">'.$row->name.'</option>';
     }
 </select> 

 get value using select box id, post driver id in controller method using            
 ajax function call model method in your controller method and put this        
 driver id in your model method's parameter and fetch reult data in success funtion     

    $('#selectid').on('change', function() {
      var value = this.value; 
      var val;                                  
    var url = <?php echo base_url('admin/new_booking_validation'); ?> 
        $.ajax({
        url: url,
       type: 'POST',
       data: { val: value}, 
       success: function(result){
       //now populate the mobile number in the select box. 
                    }});
            })

答案 2 :(得分:0)

我会这样做:

  1. 使用PHP foreach(您已经做过)填充第一个选择(驱动程序);
  2. 不要用PHP填充第二个(移动)选择。让它空着;
  3. 创建一个函数,该函数获取在驱动程序选择中选择的值并通过ajax提交;
  4. 获取值并填充移动选择;
  5. 现在我的朋友,我认为你的问题会随之改变。我是对的吗?

    我希望它有所帮助!