Reputation: 183
I am trying to call a javascript function from code behind on the button click event. below is my javascript code.
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "strScript", "javascript:clearBox();", true);
and the function is
<script type="text/javascript">
function clearBox() {
alert("Test");
}
</script>
I get an error "Object expected"
Upvotes: 0
Views: 1580
Reputation: 12815
You should use OnClientClick property of a button:
<asp:Button runat="server" OnClientClick="clearBox()" />
RegisterClientScriptBlock
will only place a piece of code on a page:
<script type="text/javascript">
javascript:clearBox();
</script>
And this will not work as it is not a valid code (because of javascript:
which is used for anchors to run js from href: <a href="javascript:some_code_here()"></a>
)
Another option, if you want RegisterClientScriptBlock
is to use addEventListener to assign onclick handler to your button. Here is code snippet for this (cross browser and pure JS). It may be used like this:
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "strScript", "addListener('"+button.ClientID+"', 'click', clearBox);", true);
But it is better to replace RegisterClientScriptBlock
with [RegisterStartupScript](http://msdn.microsoft.com/en-us/library/z9h4dk8y.aspx)
where first one may be called before all HTML is loaded and there may be no button yet.
Upd
Well, thanks to hvd. He reminded me that there are labels in JS and actually javascript:clearBox()
is a valid code, but it will not do what OP wants
Upvotes: 4
Reputation: 1918
Use this code:
Page.ClientScript.RegisterStartupScript(this.GetType(), "Error", "clearBox();", true);
Upvotes: 0