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:
[csharp]btnSubmit.Attributes.Add(“onclick”,”javascript:this.disabled=true;”);[/csharp]
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!
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
Since an onclick event (or any other event) cannot be anything BUT javascript, the inclusion of the “javascript:” protocol in the event code is wrong! It may work, but it shouldn’t, and should never be used. The only place the “javascript:” protocol is really necessary is when javascript code is used where a URL is expected, for example in an anchor’s href tag.