简体   繁体   中英

Ajax load select option Dynamically

I'm still new in javascript and ajax, i'm trying to create ajax show current category on my html select in my CodeIgniter project, the code is below:

Here's HTML:

<select class="form-control" name="category" id="category" onclick="loadCategory();">
   <option value="">Choose</option>
   <option>&nbsp;</option>
   <option>&nbsp;</option>
</select>

Here's Javascript:

function loadCategory()
{
 var url = "<?php echo site_url('home/ajax_show_category_options');?>";
 $('#category').load(url);
 return false;
}

Here's my controller:

public function ajax_show_category_options()
  {
    $category = $this->db->get('category')->result();
    $data = "<option value=''>-- Choose--</option>";
    foreach ($category as $rowCategory) {
      $data .= "<option value='".$rowCategory->id."'>".$rowCategory->name."</option>";
    }
    echo $data;
  }

When i clicked select option, will execute loadCategory() and then append the select with current category list. The question is after i choose the category, the select option will running loadCategory() over again and the value option that i choose will be empty. How to stop loadCategory() after i choose option? Thanks.

To keep this simple, Set a global boolean variable . Set it's value to true and check if it is true before performing ajax call . Consider below example.

var loadedOptions=false;//global variable
function loadCategory()
{
    if(!loadedOptions){
       var url = "<?php echo site_url('home/ajax_show_category_options');?>";
       $('#category').load(url,function(){
           loadedOptions=true; //set it to true once request is done
       });
    }
    return false;
}

Furthermore, you can also try unbinding click event on select element with off [Check for the usage of off based on jquery version you are using].

For ex

 
 
 
  
  function loadCategory() { var url = "<?php echo site_url('home/ajax_show_category_options');?>"; $('#category').load(url,function(){ $("#category").off('click'); }); return false; }
 
  


Try using removeAttr to remove onclick from select element as below:

 $('#category').load(url,function(){ $("#category").removeAttr('onclick'); }); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM