Add confirmation popup to dropdownlist in ASP.Net 2.0

by Joe Payne 28. October 2010 11:12

Today I was faced with what seemed a relatively minor task of adding a confirmation to the action button associated with dropdownlist of choices.  The concept was to add a simple popup for only the Delete choice in the dropdownlist choices.

The solution is simple but requires some Javascript.  Given I'm a pure ASP.Net 2.0 coder, this proved more of a challenge than I expected.  Here's the final solution:

First you have to insert two small javascript functions in the top of the HTML section of your ASPX page.

   1: <script type="text/javascript">
   2:  
   3: functionInsert_Confirmation() 
   4:  
   5: { 
   6:      if (confirm("Are you sure that you want to delete the selected order(s)? This task cannot be undone. Click 'OK' to delete the selected orders, or 'Cancel' to return to the order search display."))return true;
   7: else
   8: return false; 
   9: }
  10:  
  11: function CheckIfDeleteSelected() 
  12: { 
  13: var selObj = document.getElementById('<%= BatchAction.ClientID %>');
  14: if (selObj.value === "DELETE") 
  15: { return Insert_Confirmation(); } 
  16:  
  17: </script>

NOTE:  You must change the BatchAction.ClientID to ID value of the control for your dropdownlist.  In my case, the ID of the control is 'BatchAction'.

Now all you have to do is hook up the Javascript function to the ClientClick event of the action button like this:

   1: <asp:Button ID="BatchButton" runat="server" Text="GO" OnClientClick="return CheckIfDeleteSelected();" />

What's really nice is you can still do your normal server-side click event if you want.  In the example above, this has been removed.  But it does work nicely firing first the client-side click event and then the server-side if the user confirms.

Tags:

AC7 Articles

Month List