1

I have below JavaScript function in my aspx page:

<script>
    function ShowMessage() {
        alert("Hello World");
    }
</script>

I want to use this function in my cs page on button click event:

<asp:Button ID="MyButton" runat="server" Text="Click Here" OnClick="MyButton_Click" />

Now this code works fine:

Page.ClientScript.RegisterStartupScript(this.GetType(), "myScript", "alert('Hello World');", true);

But this code dose not work:

Page.ClientScript.RegisterStartupScript(this.GetType(), "myScript", "ShowMessage();", true);

What's wrong in my code? What's the possible reason?

4
  • Whats the error you are getting? Please check the source html in browser to check if the file has ShowMessage function. Commented Jun 15, 2016 at 18:46
  • I checked the page source and i found my function in page Commented Jun 15, 2016 at 18:49
  • Can you please update the question with the page source. Commented Jun 15, 2016 at 18:50
  • Use the browser's dev-tools to see the javascript console. Any errors mentioned there? Commented Jun 17, 2016 at 6:35

3 Answers 3

1

You need to expose your ShowMessage() function to a scope that your DOM has access to.

You can try:

window.ShowMessage = function() {
  alert("Hello World");
}

Another option is to move your <script></script> containing your function ABOVE the DOM element that needs it:

<script>
  function Foo() {
    alert('Bar');
  }

</script>

<button onclick="Foo()"></button>
Sign up to request clarification or add additional context in comments.

Comments

1

You can use onclientclick

<asp:Button ID="MyButton" runat="server" Text="Click Here" onclientclick="ShowMessage()" />

1 Comment

The OP might want a server-side event, to execute some server code before that message shows.
0

Try this:

<script>
    $('#idOfButton').click(
        function() {
            alert("Hello World"); 
        }
    );
</script>

Note: use JQuery for this code and paste this on the end of your HTML page.

Hope this will help

1 Comment

The OP might want a server-side event, to execute some server code before that message shows.

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.