简体   繁体   中英

external javascript file from asp.net C# page

i have some javascript functions written in an external javascript file. and i have included the file in my asp.net page head section. however im not able to understand how do i call the functions from the code behind file. eg, i want to call a certain function 'tacount' on onkeypress event of a textbox. how can i possible do that?

You can't call client side functions from server side code.

You could emit javascript to call these functions from your server side code, but this can get very messy.

Instead of attaching javascript functions to server side events, do so on the client side.

Use a library such as jQuery to attach the event to your textbox on the client side.

Have a look here at all the javascript calls you can make from code behind but basically all you have to do in your code behind call the following:

ScriptManager.RegisterStartupScript(this,this.getType(),"tacount",'tacount();',true);

This will then be triggered once the post back is completed on the client side, it is however advised to rather call javascript only from client side.

EDIT :

The fact that your file is in an external javascript file does not matter given that the browser will call it the same as inline javascript.

All you have to do is call the function as usual in your designer code ie

<asp:TextBox runat="server" onkeypress='return tacount();'/>

If you want to call a JavaScript function from your Code Behind file, you should use the code as suggested by @TBohnen.jnr ie :

ScriptManager.RegisterStartupScript(this,this.getType(),"fnMyFunctionNameFromServiceSide_tacount",'tacount();',true);

However, you should note that the fnMyFunctionNameFromServiceSide_tacount should not be present in your markup code or any included javascript file.

If you want to call the javascript function from an externally included javascript file use the following code:

<asp:TextBox id="myTextBox" runat="server" onkeypress="javascript: return tacount();"/>

However, if the above does not work for you then it means that the function could not be found. In this case I would suggest you to use FireBug to find the exact cause for not finding the javascript function. Could be that the function itself is not present or there is some javascript error inside the function itself.

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM