选择下拉菜单时如何自动填充文本框

时间:2019-09-08 13:13:51

标签: javascript php ajax codeigniter

我正在尝试在选择下拉列表时自动填充文本框。我已经尝试了一些代码,但是没有任何反应,我已经在代码中包含了jquery文件。

我有一个名为services的数据库表,列为service_id,service_name,service_price。

这是我的视图

   <div class="form-group-inner">
   <div class="row">
   <div class="col-lg-1">
   <label class="login2 pull-right pull-right-pro">Service</label>
   </div>
   <div class="col-lg-4">
   <div class="form-select-list">
   <select class="form-control custom-select-value" id="service_name" name="service_name">
   <option>Select Service</option>
   <?php foreach ($service as $services): ?>
   <option value="<?php echo $services->service_id; ?>"><?php echo $services->service_name; ?></option>
   <?php endforeach; ?>
   </select>
   </div>
   </div>
   </div>
   </div>

   <div class="form-group-inner">
   <div class="row">
   <div class="col-lg-1">
   <label class="login2 pull-right pull-right-pro">Price</label>
   </div>
   <div class="col-lg-4">
   <input type="text" id="price" name="price" class="form-control"  />
   </div>
   </div>
   </div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function () { 
    $('#service_name').on('change', function() {
    var service_id=$("service_name").val();
    $.post("<?php echo base_url();?>/records/getprice/" + service_id,

    function(data){
    $('#price').val(data.service_price);
    });
}
<script>

控制器

    function add_form($patient_id){
        $data['service']=$this->services_model->get_all_services();
        $data['value'] = $this->patient_model->get_selected_patient($patient_id);
        $this->load->view('header/header');
        $this->load->view('Records/add_records',$data);
        $this->load->view('footer/footer');
    }

    function getprice($service_id){

        $laiza=$this->db->get_where("services",array("service_id"=>$service_id));
        foreach ($laiza->result() as $row){
            $arr = array('service_price' => $row->service_price);
            header('Content-Type: application/json');
            echo json_encode($arr);
        }

    }

我希望当我从下拉列表中选择数据时,文本框将根据所选项目的下拉列表填充价格

1 个答案:

答案 0 :(得分:0)

获取Service_Name值时缺少ID选择器#

将其更改为

  

var service_id = $(“#service_name”)。val();

  

var service_id = this.value;

<script>
$(document).ready(function () { 
    $('#service_name').on('change', function() {
    var service_id=$("#service_name").val();
    $.post("<?php echo base_url();?>/records/getprice/" + service_id,

    function(data){
    $('#price').val(data.service_price);
    });
}
<script>