views:

114

answers:

3

Hey All,

I've got a piece of JavaScript that clears the data in a text box. The code works fine on a standalone page, but on the master page its not working.

On the default page my JavaScript is:

    <script type="text/javascript">

    function doClear(searchBox) {
        if (searchBox.value == searchBox.defaultValue) {
            searchBox.value = ""
        }
    }

</script>

And I this is what I'm doing to attach the OnClick property:

protected void Page_Load(object sender, EventArgs e)
{
    TextBox1.Attributes.Add("onclick", "doClear(searchBox);");
}

The error is 'searchBox' is undefined!

Any help is greatly appreciated.

Matt

+3  A: 

You will have to do something like,

protected void Page_Load(object sender, EventArgs e)
{
    TextBox1.Attributes.Add("onclick", "doClear('" + TextBox1.ClientId + "');");
}

When you use Master Pages, ASP.NET may change the client id of your HTML elements to make sure that they are unique. See http://odetocode.com/Articles/450.aspx, look at section named 'Name Mangling'.

SolutionYogi
A: 

ASP.NET pages alter your element id's. Instead of calling doClear(searchBox), I'd change the function so it takes an HTML element and call doClear(this);

Jon Galloway
A: 

Why don't you take a look at the source of your page? Its all that the javascript can get access to after all. Do you see 'searchBox' in their at all? You have to look up Textbox1.ClientId and this will then reference the control you're after.

m.edmondson