chronister2 Posted November 14, 2013 Share Posted November 14, 2013 I am trying to create a simple jquery function that responds to a click, runs an $.post() function in jquery and then changes the HTML. It works as expected the first click. The second time I click it does not fire. It seems that newly created ID of either eip_on or eip_off is not dected in the DOM to trigger the click and change things again. This link is created on page load with PHP based on a session var. I am trying to create a simple hyperlink to toggle this on and off. $('#eip_on').on('click', function(event){ event.preventDefault(); $.post("/lib/php/login.functions.php", { toggle_eip: true} ) $('#eip_block').html('<span class="eip_toggle">Edit Mode: ON. <a id="eip_off" href="#" > Turn Off</a></span><br /><br /><label><input id="update_page" type="image" src="/images/save_changes.png" /></label>'); }); $('#eip_off').on('click', function(event){ event.preventDefault(); $.post("/lib/php/login.functions.php", { toggle_eip: true} ) $('#eip_block').html('<span class="eip_toggle">Edit Mode: OFF. <a id="eip_on" href="#" > Turn On</a></span>'); }); Thanks in advance. Nate Quote Link to comment https://forums.phpfreaks.com/topic/283880-simple-toggle/ Share on other sites More sharing options...
requinix Posted November 14, 2013 Share Posted November 14, 2013 (edited) $('#eip_on').on('click', function(event){That will find all the existing elements with id=eip_on and attach onclick handlers to them. Your code creates and destroys those elements in the handlers so the new ones don't exist when the handlers are being attached. .on() Direct and delegated events Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on(). To ensure the elements are present and can be selected, perform event binding inside a document ready handler for elements that are in the HTML markup on the page. If new HTML is being injected into the page, select the elements and attach event handlers after the new HTML is placed into the page. Or, use delegated events to attach an event handler... Rather than bind the handlers to the eip_on and eip_off elements, bind them to a parent element that doesn't change, like #eic_block, and use a selector to pick which descendant elements actually trigger the event. $('#eic_block').on('click', '#eip_on', function(event){ Edited November 14, 2013 by requinix Quote Link to comment https://forums.phpfreaks.com/topic/283880-simple-toggle/#findComment-1458172 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.