CLICK功能正常,但ON CHANGE无法在多选框上运行

时间:2017-10-23 05:10:48

标签: jquery ajax codeigniter

这是我的JQuery代码 -

$(document).ready(function(){

    //code for validation
    $("#categoryid").on("change", function() {
        var categoryid = $(this).val();
        $.ajax({
           type: "POST",
           url: "<?php echo site_url('user/order/getItem') ?>",
           data: {'categoryid': categoryid},
           cache: false,
           success: function(data)
           {
              $("#itemid").html(data);
           } 
       });
    });

    $("#itemid").on("change", function() {
        var itemid = $(this).val();

        alert(itemid);

    });
});

第一个(#categoryid)运作良好。但第二个(#itemid)不起作用。如果我将“更改”更改为“点击”它可以工作,但我很惊讶为什么它不工作“更改”功能。

<div class="form-group">
   <label>Select Category:</label>
       <select class="form-control" id="categoryid" autofocus>
       <?php
       $url = site_url('user/category/showCategoryJson'); // path to your JSON file
       $data = file_get_contents($url); // put the contents of the file into a variable
       $results = json_decode($data,true); // decode the JSON feed
       foreach ($results[0] as $key => $cat) { 
       ?>
           <option value="<?php echo $cat['categoryid']; ?>"><?php echo $cat['categoryname']; ?></option>
       <?php } ?>
       </select>
 </div>
 <div class="form-group">
     <label>Select Item:</label>
     <select class="form-control" id="itemid">
     </select>

 </div>

这是我的控制器 -

public function getItem(){
    $data = array(
        'categoryid' => $this->input->post('categoryid')
    );

    $this->load->model('user/order_model');
    $res = $this->order_model->selectItem($data);

    if($res){           
        foreach ($res as $result) {
            echo "<option value=". $result['itemid'].">".$result['itemname']."</option>";
        }
    }

}

和输出图片 - enter image description here

2 个答案:

答案 0 :(得分:0)

在您成功的ajax调用中尝试此代码

              $.each(data,function(i,data){
                  $("#itemid").append($('<option>', {
                        value : data,                                       
                        text : data
                    }));    
             })

答案 1 :(得分:0)

你能试试吗?

jQuery(document).on('change','#itemid',function(){

})