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

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
});

Leave a Comment