CodexBloom - Programming Q&A Platform

jQuery .on() optimization guide with dynamically populated table rows after AJAX call - won't trigger event handlers

๐Ÿ‘€ Views: 1572 ๐Ÿ’ฌ Answers: 1 ๐Ÿ“… Created: 2025-06-11
jquery ajax event-handling JavaScript

After trying multiple solutions online, I still can't figure this out... I'm working with a frustrating scenario with jQuery where I need to bind click events to buttons inside table rows that are added dynamically via an AJAX call. I'm using jQuery version 3.6.0. After the AJAX call completes, I can see the new rows being added to the table, but when I try to click the buttons inside these rows, nothing happens. I tried using `.on('click', 'selector', function() {...})`, but it seems not to be effective. Hereโ€™s the relevant part of my code: ```javascript // Function to load data and populate the table function loadData() { $.ajax({ url: 'https://api.example.com/data', method: 'GET', success: function(data) { let tableBody = $('#myTable tbody'); tableBody.empty(); // Clear previous rows $.each(data, function(index, item) { let row = `<tr> <td>${item.name}</td> <td><button class='myButton' data-id='${item.id}'>Click Me</button></td> </tr>`; tableBody.append(row); }); }, behavior: function(xhr) { console.behavior('AJAX behavior:', xhr); } }); } // Attempting to bind click event using .on() $(document).ready(function() { $('#myTable').on('click', '.myButton', function() { alert('Button clicked! ID: ' + $(this).data('id')); }); }); ``` After calling `loadData()`, the button click event doesn't fire. I confirmed that the buttons are in the DOM by inspecting the elements, but the event doesnโ€™t seem to trigger at all. Is there something Iโ€™m missing in the way Iโ€™m binding the event or is there a better approach for handling events on dynamically created elements? Any insights would be appreciated. My development environment is macOS. Any help would be greatly appreciated! This is part of a larger application I'm building. What are your experiences with this?