0

How do I run this javascript from code behind C# during page load? Thanks a lot and many thanks in advance.

<script type="text/javascript">
document.onkeydown = function (event)
{
     event = (event || window.event);
     if (event.keyCode == 20)
     {
          alert('Caps not allow');
     }
}
</script>
3
  • Isn't that javascript will already lood on page load? I think we are missing what you are trying to achieve. Can you give more details? Commented Aug 21, 2020 at 15:23
  • Is this in ASP.NET? If so, WebForms or MVC? Something else? Commented Aug 21, 2020 at 15:39
  • I am so sorry. What I am trying to achieve is that instead of putting the JavaScript in the HTML page. I would like to load the JavaScript from asp.net webforms code behind using c# during page load. Thanks Commented Aug 21, 2020 at 17:16

1 Answer 1

1

Try using the RegisterStartupScript method.

Example in c#:

private void Page_Load1(object sender, System.EventArgs e)
{
    string js = "document.onkeydown = function (event) { event = (event || window.event); if (event.keyCode == 20) { alert('Caps not allow'); } }";

    ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "capscheck", js, true);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.