Bind events on dynamic created elements inserted by AJAX (check box)

I am new with jQuery. I have written a code to add up products from one table to other on checked dynamically like this FIDDLE : this code is working fine for me as you can see in fiddle.

Now I have manipulated this code by generating this product list (of table 2) dynamically using ajax,now this code doesn't work for me..

As I have thought about this defect, the thing that I am thinking that my all CSS and JS scripts get loaded with the loading of page BUT THIS CHECKBOX (TABLE 2) GETTING LOADED DYNAMICALLY THAT IS WHY JS IS NOT ENTERTAINING THIS ....

So how to fire event function on dynamic loaded input field... just want this script to get improved : JQUERY 1.6.4

Here is my view:

<div class="_25">
    <?php echo form_dropdown('class', $dropdown_class,'','id="clas"'); ?>
</div>

<div class="_25">           
    <?php echo form_dropdown('section',$dropdown_section); ?>
</div>  

<table class="table" border="1">
    <thead><tr>
        <th>Select</th>
        <th>Cause</th>
        <th>Monthly Charge</th>
    </tr></thead>

    <tbody id="selectedServices"></tbody>

    <tr>
        <td>Total-</td>
        <td>Fee</td>
        <td id="total">1500</td>
    </tr>
</table>

<!-- product list (will generate dynmiclly)like tble 2 in fiddle -->
<table id="abcd" class="table" border="1">
    <thead><tr>
        <th>Select</th>
        <th>Cause</th>
        <th>Monthly Charge</th>
    </tr></thead>
    <tbody id="name_sec">
        <!-- here your dat will appear as per selection of class ajax check the below function and related controller mthod 
        the value will come with chk box for selection ad prepering the data-->
    </tbody>
</table>

Here is my script:

<script language="javascript">
jQuery(function ($) {

    $("#clas").change(function() {
        var send_data=$("#clas").val();

        $.ajax({
            type:"post",
            url:"show_additional_fee_chkbox_select",
            data:"send_data_post_for_chkbox="+send_data,
            success:function(data){
                $("#name_sec").html(data);
            }
       });
    });

    $(":checkbox").change(function () {
        // Toggle class of selected row
        $(this).parent().toggleClass("rowSelected");

        // Get all items name, sum total amount
        var sum = 1500;
        var arr = $("#abcd :checkbox:checked").map(function () {
            sum += Number($(this).parents('tr').find('td:last').text());
            return $(this).parents('tr').clone();
        }).get();

        // Display selected items and their sum
        $("#selectedServices").html(arr);
        $("#total").text(sum);

        $('#selectedServices :checkbox').change(function() {
            $('#selectedServices :checkbox:unchecked').parents('tr').remove();
        });
    });

});
</script>

And my controller:

public function show_additional_fee_chkbox_select()
{
    $class=$_POST['send_data_post_for_chkbox'];

    //here goes ur process to display list of extra/additional fee 

    $extra_fee_list='';    
    $sql2="SELECT * FROM fee_additional_fee where class=?";
    $query2 = $this->db->query($sql2,$class);

    foreach ($query2->result_array() as $row2) {
        $extra_fee_list=$extra_fee_list.' 
        <tr>        
            <td>  
                <input type="checkbox" id="selectedServices" class="checkBoxClass" name="additional_fee_code[]"  value="'.$row2['id'].'"> Select</input>
            </td> 

            <td>'.$row2['cause_addition_fee'].'</td>
            <td>'.$row2['fee'].'</td>
        </tr>  ';

        // here again plz take input in  arry ----additional_fee_code will work for next method (cal_total_extra_fee())
    }

    echo $extra_fee_list;
}

Solution 1:

As I realized, the AJAX result data is a table row element <tr> contains data-cells <td>, inputs <input> or etc.

First Solution:

If you want to get access to an element inside data, this should do the trick:

$(':checkbox', $(data));

So, you can set an event on internal elements right after data is prepared.

// Since jQuery 1.7
$(':checkbox', $(data)).on('click', function() {});

// Or
$(':checkbox', $(data)).click(function() {});

You can also declare a global function and just insert its name to .click() or .on() method as handler.

So, just edit $.ajax section similar to the below:

$.ajax({
    type    : "post",
    url     : "show_additional_fee_chkbox_select",
    data    : "send_data_post_for_chkbox="+send_data,
    success : function(data) {
        var html = $(data);
        $('input[type="checkbox"]', html).click(onClickFunction);
        $("#name_sec").html(html);
    }
});

Here is a JSBin Demo


Second Solution

There is also another way to bind an event on inserted elements.

Using jQuery .find() method could be an option:

// Since jQuery 1.6
$('#name_sec').find(':checkbox').click(function() {
    // Do whatever you want
});

This should be placed right after $("#name_sec").html(data); in $.ajax section.


Third Solution:

By using jQuery .on() method as easy as:

// Since jQuery 1.7
$('#name_sec').on('click', ':checkbox', function() {
    // Do whatever you want
});