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:

[js]btnSubmit.Attributes.Add(“onclick”, “javascript: (js code);”);[/js]

Example uses include:

JavaScript confirmation boxes:

[csharp]btnSubmit.Attributes.Add(“onclick”,”javascript:if(confirm(‘Are you sure?’)== false) return false;”);[/csharp]

JavaScript alerts:

[csharp]btnSubmit.Attributes.Add(“onclick”,”javascript:alert(‘Danger Will Robinson!’);”);[/csharp]

JavaScript disabling the button:


JavaScript generating popup windows:

[csharp]btnSubmit.Attributes.Add(“onclick”,”window.open(‘page.html’,’Window1′, ‘menubar=no,width=800,height=600,toolbar=no’);”);[/csharp]

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!

Pin It on Pinterest

Share This
%d bloggers like this: