Get at the ASP.NET Ajax control name with the BehaviorID property

If you have ever worked with ASP.NET and binding data to a repeater control or placing content inside master pages, you're probably familiar with how ASP.NET renames the control to make it unique.  This makes web developers have many headaches as they try to get to those controls from javascript.  Here's a scenario I was recently faced with:  I had a web control using some controls from the ASP.NET Ajax control toolkit, the TextBoxWatermarkExtender and a DropDownExtender, and a regular textbox for user input.  The web control containing all of those controls was placed on a page that also had a master page (as you can tell there is going to be some renaming once its rendered to the browser)  The action to perform was to check if the textbox was empty and display a message to the user.  The problem was getting to that textbox, checking the text and not getting the watermark text.  The answer to this is in the BehaviorID property of the TextBoxWatermarkExtender.  With this id you can give the name of the control and use that in javascript to find the control. 

First set the BehaviorID in the control that you're using.  That BehaviorID you give it will be the one you use in javascript to find that control.

So, the solution in javascript would be something similar to this:

    //this finds the object on the page or any control with a behavior id

    var obj = $find("watermarkextender_behaviorID_here"); 

 

    //the get_Text method returns the text of the control, and NOT the watermark text

    var objectText = obj.get_Text();

 

    if(objectText == '')

    {

        alert("Hey User! Enter something useful!");

        return false;

    }