How can I dynamically add drupal behaviors to a form from php using ajax? I am creating a form which dynamically changes based on the value of a select element.  What happens is this:


The user selects a value from the select element
The select element uses Drupal's ajax methods to reload the form, now with some new elements for further configuration
Some of the new elements need to be turned into jQuery widgets.


Now, the obvious solution here is to use behaviors to run the widget initialization code.  The issue is that I don't know ahead of time which elements need to have what code run on them.  I will only know that at the time the ajax portion of the form loads.

Currently, my solution is to have a very short JavaScript file which is solely responsible for adding new behaviors which in turn run the jQuery UI code that I need.

An alternate solution is to pre-load all of the possible configuration elements and inject all of the behaviors ahead of time.  For various reasons this isn't a good idea, not least because I rather like lazy loading.

My question is: is there some way to attach behaviors in php through Drupal's ajax mechanism, like there is a way to modify the settings?
Yes you can attach Drupal Behaviors to newly added elements (DOM nodes):

You can check ahah.js (in Drupal.ahah.prototype.success):

// Attach all javascript behaviors to the new content, if it was successfully
// added to the page, this if statement allows #ahah[wrapper] to be optional.
if (new_content.parents('html').length &gt; 0) {
  Drupal.attachBehaviors(new_content);
}


Or if your script creates the elements (answer on stackoverflow about drupal-behaviours):

var newNodes = $('&lt;a href="#"&gt;Hello&lt;/a&gt; &lt;a href="#"&gt;World&lt;/a&gt;').appendTo('#someDiv');
Drupal.attachBehaviors(newNodes);