John Chapman

Programmatically Adding JavaScript Events to Buttons in ASP.NET C#

Share on TwitterShare on LinkedInShare on TumblrSubmit to StumbleUponSave on DeliciousDigg ThisSubmit to reddit

When working with buttons in C# for ASP.NET, it is often helpful to add JavaScript actions programmatically to the button that trigger when clicked in addition backend C# code. This can be used to generate pop-ups, create alerts and confirmations, disable buttons, etc.

The syntax for adding the JavaScript is:

btnSubmit.Attributes.Add("onclick", "javascript: (js code);");

Example uses include:

JavaScript confirmation boxes:

btnSubmit.Attributes.Add("onclick","javascript:if(confirm('Are you sure?')== false) return false;");

JavaScript alerts:

btnSubmit.Attributes.Add("onclick","javascript:alert('Danger Will Robinson!');");

JavaScript disabling the button:

btnSubmit.Attributes.Add("onclick","javascript:this.disabled=true;");

JavaScript generating popup windows:

btnSubmit.Attributes.Add("onclick","window.open('page.html','Window1', 'menubar=no,width=800,height=600,toolbar=no');");

You can pretty much add any JavaScript function programmatically using this code. This can also be used to add JavaScript triggers to other elements, such as Hyperlinks and Images. Happy coding!

Share on TwitterShare on LinkedInShare on TumblrSubmit to StumbleUponSave on DeliciousDigg ThisSubmit to reddit

John Chapman

Hello, I'm John Chapman. I am a SharePoint developer living in Mesa, Arizona. I develop solutions using ASP.NET, C#, jQuery, SQL, SharePoint, etc, and I thrive on the challenge of writing code to overcome the impossible, annoying, or otherwise difficult obstacles.

Website - Twitter - More Posts

3 Comments

  • Hi there!

    Thanks for the post.

    I have a delete button with an onclick method which runs in code behind. (OnClick=”btnDelete_Click”).

    How do I make the btnDelete_Click() function quit if the user click “No”? I’ve added your code:

    btnDelete.Attributes.Add(“onclick”, “javascript:if(confirm(‘Are you sure?’)== false) return false;”)

    But the code to delete a record still executes thereafter.

    Regards,
    Lochner

  • You might need to add a return value:

    if (confirm(‘Are you sure ?’) == false)
    {
    window.event.returnValue = false;
    return false;
    }
    else
    {
    window.event.returnValue = true;
    return true;
    }

  • Sir, I am using a javascript confirmation box, i have already included a onclick event in my button , i want to include this javascript function , how can i do it ,can u suggest me.

    thanking you in advance

Leave a comment

John Chapman