– getting user confirmation before a postback

In web applications, it is common to have dozens — if not hundreds — of user controls that perform postbacks to the server, actions initiated by a user such as a button click. Often before a save, delete, or other critical action is performed, it is desirable to ask the user if they are sure.

In web applications, buttons and other controls have two event properties that we are concerned with: onClick , and onClientClick .

The onClick event calls a specified function in the code-behind file. At this point, the postback has occurred, and any confirmation would have to take place with another rendered page — meaning lots of wasted time and wasted resources.  With the onClientClick event, we can interrupt the onClick event with our own javascript function or inline statement.

Using jQuery, we can bind function to all of these “confirm-able” user controls, which will interrupt the default post-back behavior  presenting users with a confirmation dialog box:

Using this method, we can target all user controls with the CSS class confirm. Additionally, if we wanted a broader reach, we could modify the jQuery selector to  input[type=button] or for all buttons, or all links.

The confirm box  var response = confirm("Are you sure?"); used in this example is a default JavaScript confirmation dialog box — which will be rendered differently per browser or platform — but you could easily swap this for any other confirmation script or function that returns a boolean value.

Author: Michael Jasper

Michael is a Web Developer located in Northern Utah. When not programming, he enjoys spending time with his family, exploring the great-outdoors, and hit-and-miss cooking experiments.