Reputation: 187
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
Upvotes: 0
Views: 264
Reputation: 30922
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.
Upvotes: 0
Reputation: 53165
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);
Upvotes: 0
Reputation: 32243
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'.
Upvotes: 3