Hussain Fakhruddin
Blogging about tech stuff

Follow

Blogging about tech stuff

Follow
Reinitializing jquery event on ajax response

Photo by Goran Ivos on Unsplash

Reinitializing jquery event on ajax response

Hussain Fakhruddin's photo
Hussain Fakhruddin
·Jan 31, 2012·

1 min read

I had a jquery change event attached to a checkbox that was part of a div.

<div id="test-div">
<input type="checkbox" checked="checked" value="1" class="test-chkbox" />
</div>

Using the following JQuery code a change event was attached to the above check-box

$(".test-chkbox").change(function () {
    $.ajax({
        type: "GET",
        url: "some-action",
        data: this.value,
        cache: false,
        success: function(response) {
            $("#test-div").replaceWith(response);
        }
    });
});

Response of ajax contained the same check-box but the change event was no more attached to it, so to solve the issue I changed jQuery code as specified below.

$(document).on("change", ".test-chkbox", function () {
    $.ajax({
        type: "GET",
        url: "some-action",
        data: this.value,
        cache: false,
        success: function(response) {
            $("#test-div").replaceWith(response);
        }
    });
});

The above change made sure that the change event is always attached to the check-box even after the ajax response.

Note: Older versions of jQuery use .delegate and .live instead of .on

 
Share this