CodexBloom - Programming Q&A Platform

jQuery .on() optimization guide for dynamically added elements in a multi-step form

👀 Views: 45 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-05
jquery event-delegation dynamic-content JavaScript

Hey everyone, I'm running into an issue that's driving me crazy. I'm having trouble with event delegation using jQuery's `.on()` method for a multi-step form where steps are loaded dynamically. I have a form that shows different fields based on the user's previous selections, and I attach event listeners to buttons that navigate between these steps. However, when the buttons are rendered in the DOM after the initial page load, my click handlers aren't firing. Here's a simplified version of what I have: ```javascript $(document).ready(function() { // Initial event binding for the first step $('#nextStep').on('click', function() { // Logic to show the next step $('#step1').hide(); $('#step2').show(); }); }); ``` When I click the 'Next' button, it works fine for the first step, but once I get to step 2 and attempt to go to step 3, I have another button that's added dynamically: ```javascript // This button is added to the DOM after step 2 $('<button id="nextStep2">Next Step</button>').appendTo('#step2'); ``` I've tried reattaching the event handler after the new button is added, but it still doesn't trigger: ```javascript $('#nextStep2').on('click', function() { $('#step2').hide(); $('#step3').show(); }); ``` I also tried using event delegation like this: ```javascript $(document).on('click', '#nextStep2', function() { $('#step2').hide(); $('#step3').show(); }); ``` However, I see no console errors, and nothing happens when I click the button. I'm using jQuery version 3.6.0. Any suggestions on how to make sure the event is correctly attached to dynamically added elements? This is becoming quite frustrating!