CodexBloom - Programming Q&A Platform

jQuery .on() event not firing for dynamically added elements in nested loops

👀 Views: 73 💬 Answers: 1 📅 Created: 2025-06-13
jquery event-handling dynamic-content JavaScript

I need help solving I'm optimizing some code but I'm working with an scenario where I'm trying to bind a click event using jQuery's `.on()` method to dynamically created elements inside a nested loop. I have a table where rows are generated based on user input, and each row has a button that should trigger a function when clicked. However, the click event only works for the first set of rows created, and not for any subsequent rows. Here's the relevant part of my code: ```javascript $(document).ready(function() { $('#addRowButton').on('click', function() { let newRow = '<tr><td>Data</td><td><button class="action-button">Click me</button></td></tr>'; $('#myTable tbody').append(newRow); }); // Binding the click event using .on() $('#myTable tbody').on('click', '.action-button', function() { alert('Button clicked!'); }); }); ``` I expected the alert to fire whenever I click any button in the dynamically added rows. Instead, the alert only shows up for the buttons in the initial rows. I’ve double-checked that the HTML structure is correct, and no errors are logged in the console. I tried moving the `.on()` call outside of the `#addRowButton` click handler and resorting to `.delegate()`, but it hasn’t resolved the scenario. I'm using jQuery version 3.6.0, and this behavior is consistent across multiple browsers. Is there something I'm missing with how events are bound to dynamically created elements? Any insight into why this click event isn't triggering for newly added rows would be appreciated. My development environment is Ubuntu. My development environment is Windows 11. Any examples would be super helpful. The project is a desktop app built with Javascript. What am I doing wrong?