Rasclatt Rasclatt - 11 months ago 72
Ajax Question

How to bind dynamic content to document-ready events?

I am not amazing with jQuery or JavaScript for that matter, so there is probably a duplicate question on this, but I am not sure how to phrase my search. I think I have to use

but I am not sure how to implement it properly if so, or perhaps it's not possible in this scenario.

I have three pages, my
page with HTML, a
page that serves dynamic content into the index page via Ajax, and lastly
with all my jQuery/JavaScript.

Here is psuedo-code example:


<form id="form1">
<input type="text" name="whatever" />
<input type="submit" name="whatever_submit" disabled="disabled" class="enable" />
<form id="form2">
<input type="text" name="whatever2" />
<input type="submit" name="whatever_submit2" disabled="disabled" class="enable" />
<!-- this is where the dispatch page will deliver content to -->
<div id="drophere"></div>


$(document).ready(function() {
// Runs on page load and enables all the submit buttons
// Code to dispatch
url: '/dispatch.php',


<!-- Does php stuff, sends back this additional form -->
<form id="form3">
<input type="text" name="whatever3" />
<input type="submit" name="whatever_submit3" disabled="disabled" class="enable" />

The issue here is that the jQuery
works on
but now I am using ajax to load a form and it doesn't bind to the dynamic
because the other two are effected on document-ready. I successfully use
for interactive elements because there is a trigger (
, etc)
but it's this passive application that I don't really know how to do (maybe there is no way or maybe I am not calling the right event type?). As a workaround, I put the same enabling script into the dispatched html:

<form id="form3">
<input type="text" name="whatever3" />
<input type="submit" name="whatever_submit3" disabled="disabled" class="enable" />
So this is added at the bottom and runs as soon as the content loads to
the index.php page

This seems like a clumsy workaround, so is there a proper way to bind dynamic content to a document-ready event from javascript located on
or is the proper way to redo that piece of code to work on a click event using
similar to:

// Possibly do the form submit here...whatever I get to work

I am hoping there is a way to bind because I have a lot of other similar instances this will apply to, but I am thinking I may have to switch to per-click basis? Any assistance would be appreciated.

Answer Source

Just execute the $('.enable').attr('disabled',false); in the callback function of the ajax-call.

What you could do is using the MutationObserver which is part of modern browser JS engines: https://developer.mozilla.org/en/docs/Web/API/MutationObserver