Click or submit event is not working after being loaded with ajax

If you’re loading HTML via AJAX and your jQuery isn’t working afterward, it’s likely because the event bindings are being lost when new content is dynamically inserted into the DOM. This can happen because jQuery event listeners are typically bound to elements that exist at the time the script runs, but newly injected content doesn’t have those bindings.

To fix this, you can either:

1. Use $(document).on() for dynamic event binding

Instead of directly attaching event listeners (e.g., $("#element").click()), you can use event delegation with $(document).on(). This method works for elements added after the initial page load because it delegates the event to a parent element that exists when the page loads.

$(document).on('change', '#ClickId', function () {
    // Your jQuery logic here
    alert("test!");
});

Here, $(document) is listening for any change events that happen on the #Luggage-Addon element, even if that element is dynamically loaded via AJAX.

 

2. Make sure jQuery is re-initialized after content is loaded via AJAX

Ensure that any jQuery code is executed after the AJAX content is fully loaded. If you’re using jQuery’s $.ajax() or $.load(), you can add the event binding inside the AJAX success callback.

Example with $.ajax():

$.ajax({
    url: 'your-url',
    method: 'GET',
    success: function(response) {
        $('#content-wrapper').html(response); // Load your HTML

        // Bind your event after content is loaded
        $('#ClickId').change(function() {
             alert("test!");
        });
    }
});
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments