Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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

First Answer :

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

Solution 2:

You know that when you create new objects in the site, the javascript that is written will not recognize it... Unless... You use the live method of the jQuery, which will self update his knowledge of the DOM.

Instead of:

$(my_check_box_class).click(function() {...})

Use:

$(my_check_box_class).live("click", function()
{
 var id_selecionado = $(this).attr('id');  
 $.ajax(
 {...

Got it?

Post a Comment for "Bind Events On Dynamic Created Elements Inserted By Ajax (check Box)"