0

Code from aspx.cs:

.......
button.OnClientClick = "onButtonClick(this)";
.....

Function in Javascript(written in the aspx file):

<script> 
        function onButtonClick(event) {
           ....
        }
</script>

The "program" didn't even get to the script.

2 Answers 2

1

Where are you calling your button.OnClientClick assignment? If it is in the page load or a button click event, it should work. If you are calling it in an ajax method, the button may be be rendered after the assignment, so maybe that's your problem.

protected void Page_Load(object sender, EventArgs e)
{
    Button1.OnClientClick = "clicky(this)";
}

On .aspx page, just before the closing tag:

<script>
   function clicky(e) {
      alert("click");
   }
</script>

You should be able to see onclick="clicky(this)"; when you inspect the element in the Chrome developer tools when you run the page.

Sign up to request clarification or add additional context in comments.

Comments

0

Well its redundant to call a JavaScript with a asp button when you can always just use the on click method with a normal html button.

 <button onclick="onButtonClick()">Click me</button> 

However here is how you can do it with the following ways

Response.write("<script type=""text/javascript"">onButtonClick();</script>")

// OR
ClientScript.RegisterStartupScript(GetType(), "Javascript", "javascript:onButtonClick(); ", true);
// OR 
string name = "onButtonClick()";
        ScriptManager.RegisterClientScriptBlock(this, typeof(string), "Key", name, true);
// OR    
ScriptManager.RegisterStartupScript(this, GetType(), name, false); 

2 Comments

Might want to use scriptManager then.
agree with @John. the page will need a script manager <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager> as seen: javascriptshorts.com/…

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.