-1

I have filter for producttypes which is getting created as per enteries in database via ajax:

HTML Part:

<ul id="foodtype"></ul>

Ajax Code to show filter:

    function showtypes(){
        $.ajax({
          type: "POST",
          url: "ajax/incl/showtype",
          data:'',
          dataType : 'json',
          cache: false,
          success: function(records1){
                $('#foodtype').html(makefoodType(records1));
          }
        });
       }

       function makefoodType(data1){
          var tbl_body = "";
            $.each(data1, function() {
              var tbl_row = "",
                  currRecord = this;
              $.each(this, function(k1 , v1) {
            tbl_row += "<li><input type=checkbox id="+v1+" name="+v1+" /> 
                        <span style=font-size:14px>"+v1+"</span></li>";
              })
              tbl_body += tbl_row;
            })

        return tbl_body;
      } 

The categories are getting displayed properly but when i select checkbox then following code needs to be executed

 function getFilterOptions(){
   var opts = [d,de];
   $checkboxes.each(function(){
     if(this.checked){
       opts.push(this.id);
   }
  return opts;
  }

  var $checkboxes = $("input:checkbox");
  $checkboxes.on("change", function(){
    var opts = getFilterOptions();
    updateProducts(opts);

  });

I want the ID of checkbox to be pushed to page having php code. But nothing is happening on checking checkbox. Note: When i view source code then <ul id="foodtype"></ul> code remains inact.. No <li> elements are displayed :(

Gags
  • 3,759
  • 8
  • 49
  • 96

2 Answers2

0

You need to use something called event delegation. Listen on the click events on the container where checkboxes are. So after you add them dynamically, the click event will get bubbled to the container.

kaapa
  • 507
  • 4
  • 12
0

That's because var $checkboxes = $("input:checkbox"); is getting executed before ajax is complete and hence no elements.

Change to

$(document).on("change", "input:checkbox", function() {
    var opts = getFilterOptions();
    updateProducts(opts);
});

and it should work.

Harsh Moorjani
  • 648
  • 1
  • 5
  • 16