call a JavaScript function in codebehind

Posted by Nerdanalysis under JavaScript on 5/12/2012 | Points: 10 | Views : 6254 | Status : [Member] | Replies : 4
I want to call a JavaScript function in codebehind. It is working fine on the button click event, not on the pageload event. As I can understand this is a Page Life Cycle's Get and post cause. Is there anyway i can get that javascript function on the page load event.

Html code :-

</asp:Label><asp:HiddenField ID="HiddenField1" runat="server" />
<script type="text/javascript" language="javascript">
try {
var i = 1000;
document.getElementById('<%= HiddenField1.ClientID %>').value = i;
}
catch (ex) {

alert(ex);
}
</script>

Code Behind :-

protected void Page_Load(object sender, EventArgs e)
{
try
{
string abc = HiddenField1.Value;
Label1.Text = abc;
Response.Write("asdfas" + abc);
}
catch (Exception ex)
{
Response.Write(ex.Message.ToString());
}

}




Responses

Posted by: Hariinakoti on: 5/12/2012 [Member] Starter | Points: 25

Up
0
Down
i think itz not possible Nerdanalysis.We can call this function at button click event only.

Thanks & Regards
Hari

Nerdanalysis, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Denny on: 5/14/2012 [Member] Starter | Points: 25

Up
0
Down
Hi
You could go for a method of ScriptManager as I would give a demo code.


Here strScript can be your javascript code in Page Load event
You should write the JS in this fashion given below
PageLoad()
{
string strScript = @"function fn()"
+ "{"
+ "var i=1000;"
+ "document.getElementById('" <%= HiddenField1.ClientID %> "').value=i;"
+ "}";
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Script", strScript, true);
}

This is a sample ..
Change it acccording to your requirements..

Regards,
Denny Kurian

Nerdanalysis, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Denny on: 5/14/2012 [Member] Starter | Points: 25

Up
0
Down
Hi,
Since itz a hidden field you could go for ScriptManager.RegisterHiddenField(Control, String, String)

You have some methods in Script Manager to use it in the UpdatePanel
Plz check it out..

Regards,
Denny Kurian

Nerdanalysis, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Dotnetrajanikanth on: 5/15/2012 [Member] Starter | Points: 25

Up
0
Down
Page.ClientScript.RegisterStartupScript(Me.GetType(), "Key", "<Your Function Name in Javascript>", True)

eg:

Page.ClientScript.RegisterStartupScript(Me.GetType(), "SampleKey", "Validate();", True)


This will work i am using this code

____________
www.flickr.com/photos/psdesigner/

Nerdanalysis, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response