Programmatically Adding JavaScript Events to Buttons in ASP.NET C#
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!
3 Comments
Leave a comment
Follow John Chapman
SharePoint StackExchange
- http://t.co/iQpe9vD0 - #sharepoint - [SharePoint 2010 / SQL Server 2008] Query the SharePoint Object Model from a .NET SQL Server CLR Functi
- http://t.co/2dyRsdgu - #sharepoint - [SharePoint 2010] Debugging a Custom SharePoint Timer Job
- Help! FAST Search for SharePoint 2010 SQL Server Deadlocks http://t.co/3MDByzBP
Recent Posts
- [SharePoint 2010 / SQL Server 2008] Query the SharePoint Object Model from a .NET SQL Server CLR Function
- [SharePoint 2010] Debugging a Custom SharePoint Timer Job
- [SharePoint 2010] Set Access Request Email for All SharePoint Sites
- [ASP.NET / LINQ] Access GridView DataItem Properties of Anonymous Types
- [.NET / LINQ] Dynamic SQL-Like LINQ OrderBy Sorting Extension

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