How to get a reference to a Sys.UI.Behavior instance
If you attach a behavior to an element, how do you get a reference to it?
For example, on this page, there is a text box control with two behaviors attached:
<asp:TextBox ID="txtTitle" runat="server" /> <ajax:TextBoxWatermarkExtender BehaviorID="titleWatermark" TargetControlID="txtTitle" ... /> <ajax:AutoCompleteExtender TargetControlID="txtTitle" ... />
To access the client-side behaviors, you can use one of three static methods in Sys.UI.Behavior:
Sys.UI.Behavior.getBehaviorByName(element, name)
This method gets a Sys.UI.Behavior instance with the specified name property from the specified HTML Document Object Model (DOM) element.
var behavior = Sys.UI.Behavior.getBehaviorByName($get("txtTitle"), "TextBoxWatermarkBehavior");
Returns the the TextBoxWatermarkBehavior.
N.B. By default, the name of a behavior is its type, unless you explicitly specify one.
An expando attribute with the same name is created on the element, therefore, you can also access the behavior by:
var behavior = $get("txtTitle").TextBoxWatermarkBehavior;
Sys.UI.Behavior.getBehaviorsByType(element, type)
This method gets an array of Sys.UI.Behavior objects that are of the specified type from the specified HTML Document Object Model (DOM) element.
var behaviors = Sys.UI.Behavior.getBehaviorsByType($get("txtTitle"), AjaxControlToolkit.AutoCompleteBehavior);
Returns an array containing one behavior – the AutoCompleteBehavior.
N.B. This method is incorrectly named as getBehaviorByType (singular behavior) on MSDN, the actual name is getBehaviorsByType (plural behavior) as from the library source code!
Sys.UI.Behavior.getBehaviors(element)
This method gets an array of Sys.UI.Behavior objects that are associated with the specified HTML Document Object Model (DOM) element.
var behaviors = Sys.UI.Behavior.getBehaviors($get("txtTitle"));
Returns an array containing two behaviors - the TextBoxWatermarkBehavior and the AutoCompleteBehavior.
BehaviorID and Sys.Application.findComponent(id)
All the extenders in the AJAX Control Toolkit has a BehaviorID property, and if you set it to a unique string, you can use Sys.Application.findComponent(id) or simply $find(id) to get at the behavior.
var behavior = $find("titleWatermark");
Also see Getting a reference to a behavior by Bertrand Le Roy.