Add a JavaScript popup to an ASP.NET button

If you want an easy way to remind your user to check if all the information on a form is correct after clicking the button, or if you want a second "are you sure?" question to appear after clicking a button before a significant event is carried out (deleting a large amount of records), then you can use this code to add a JavaScript alert pop-up to any ASP.NET button control. Works in IE, don't know about the others yet.

<%@ Page Language="C#" %>
<script runat="server">
public void PageLoad(Object sender, EventArgs E) {
btnSubmit.Attributes.Add("onclick","javascript:if(confirm('Are you sure everything is correct?')== false) return false;");
}
void btnSubmit
Click(object sender, EventArgs e) {
        Message.Text = "You entered your name as: " + txtName.Text;
}
</script>
<html>
<head>
</head>
<body>
<form runat="server">
    Name: <asp:Textbox id="txtName" runat="server"/>
<asp:Button id="btnSubmit" onclick="btnSubmit_Click" runat="server" Text="Submit"></asp:Button><br/>
<asp:Label id="Message" runat="server"/>
</form>
</body>
</html>

You might also like...

Comments

Edward Tanguay Edward Tanguay updates his personal web site tanguay.info weekly with code, links, quotes and thoughts on web development. Sign up for the free newsletter.

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“The difference between theory and practice is smaller in theory than in practice.”