Mark Mintoff My superpower is common sense

7Mar/1134

ASP.Net JQuery Confirm Dialog

How does one go about replacing the javascript default functionality of "confirm", which despite being very useful, is terribly out of touch with modern web design?

Achieved, naturally through the use of this simple bit of code:

Over the past few days, I combed the web searching for a nice, clean and simple way to replace the confirm dialog with a stylized version; preferably with JQueryUI. All solutions and plugins which I found seemed to be concentrated towards passing in functions or URLs to be executed upon the user pressing the "Yes" button. This is insufficient. The great advantage attained from "confirm" is that it halts the form from submitting until user input is provided; something which is very very useful in ASP.Net.

What I needed was to emulate the same functionality; putting the form submission on hold, until the user has clicked "Yes" and to do nothing if "No" is pressed.

My first approach was to use a JQueryUI Dialog normally. To my great dismay, I found that the page does not even wait for user input through the use of this dialog. So much for modal.

My second approach was to resort to Pascal-based thinking; an infinite loop waiting for input. To my surprise, the dialog does not even come up when this is done, and the client side is locked under an infinite loop.

My third approach turned out to be made of the right stuff. What if the default functionality was prevented (returning false) while the dialog is presented to the user and then re-executing the click command if "Yes" is pressed? It's so simple and elegant, I'm in love with it.

Here's how it works:

  • Pass the button itself to the function "confirmDialog"
  • The variable "confirmed" is set as "false" by default.
  • First time condition check: confirmed is false, so display the dialog.
  • Return confirmed (false); hence preventing the code from executing.
  • Dialog is up
  • User presses "Yes", confirmed is set to true
  • Re-execute the button's click function
  • Second time condition check: confirmed is true, do not display the dialog.
  • Return confirmed (true); hence allowing the code to execute.

Simple no? Here's what it looks like:

If "No" is pressed, nothing happens. Confirmed is still false, hence no executions will take place. It is only when "Yes" is pressed and the button's click function is re-executed, will the action execution take place. A simple and yet elegant solution. And what's better is that it involves zero plugins.

The following is a more customizable implementation which I would suggest you make use of:

This has the advantage of dynamically creating the dialog div, as well as allowing customization of the title and dialogText. The close event also cleans up, by removing the generated dialog div.

There is one caveat, which ISĀ solvable I assure you; usage within UpdatePanels. For this I would suggest taking a look at Rick Strahl's ClientScriptProxy and writing something along the lines of:

Putting a "confirmed = false;" in the BindControlEvents() function.

I do not wish to go into too much detail about it here, but this is my implementation:

Now all you need to do is literally writing "confirmed = false;" in a function named BindControlEvents(). Personally, I like using JQuery and UpdatePanels in conjunction with each other, so I write a few things in there such as:

You can obviously customize this to suit your merry needs!

Downloadable example:

VN:F [1.9.22_1171]
Rating: 3.9/5 (26 votes cast)
ASP.Net JQuery Confirm Dialog, 3.9 out of 5 based on 26 ratings
Comments (34) Trackbacks (0)
  1. Could giv a sample code.how s d  "#dialog-confirm" generated.Do we need to create it explicitly..coz i m finding "Object doesn't support this property or method" error

    Thanks

    Prajwal

    • Hi prajwal dalmeida,

      Yes, you would have to create the markup for the dialog naturally. Follow this which gives an explanation on how to build a JQueryUI dialog.

      As for the "Object doesn't support this property or method" error, it would seem that you have not included a script reference to JQuery. As the title suggests, this function is for a JQuery Confirm Dialog.

  2. Thanks for this info, it saved my ass ;)

  3.  
    Ideally, hooking to a handler should be done unobtrusively, not inline; primarily to separate behavior (event handler) from presentation (HTML).
     
    The reason why you were stuck when you implemented an infinite-loop is because JavaScript is single threaded and thus everything runs on the same thread.  If you want to emulate multi-threading, you need to use the setInterval function which invokes its input function periodically.
     
    Also, you should access DOM elements only once (if the situation allows) and then use their reference via their contained variable.  This is because DOM traversing is expensive and should be minimized as much as possible.  In the above code, you are walking the DOM multiple times; in fact, every time the ConfirmDialog is invoked, and that's wasting resources [never the less, it's just a micro-optimization :)]
     
    As regards UpdatePanels, you should really be careful in using them (that's not to say you shouldn't of course) and the reason being that an UpdatePanel sends ALL of its contained elements back to the server whenever a partial postback is performed, and that's rarely what you want since that's usually overkill.
     
    And finally, why are you using a global variable (dialogConfirmed) instead of a local one?  Maybe I'm missing something here, but can't you use a local variable as a flag for signalling dialog confirmation vs clicking cancel?
     
    One final pet-peeve:  when using a variable as a flag, you don't need to set it to false explicitly because it's default value is 'undefined', which is a falsy value already :-)

    • Hi Dreas!

      What I did there wasn't actually an attempt at multi-threading, it was a Quick-Basic or Pascal based approach borne out of frustration! What I intended to do was pause the thread to wait for input. I attempted setIntervals at one point but decided it was not worth the effort.

      I am well aware that accessing DOM elements is expensive, however as you might note, there is no reason in this particular scenario to store the elements within variables as the elements references are being accessed once per time that the dialog is invoked. Since deletion (which is not checkbox based) usually happens within a grid with several rows, it is good that the element selection is in a sense dynamic.

      I am also aware of how UpdatePanels work. They also go through the entire page life cycle (unless the flow is controlled properly). However I considered it worthy to mention how one would go about working with this solution within UpdatePanels due to their popularity.

      The local vs global variable argument is easy to explain. I am assuming you mean a local variable within the function ConfirmDialog. In that case, the entire process would not work as intended, as by invoking the click method from the button, the ConfirmDialog function is called upon again and the value needs to be retained. If you do not make the variable global, then dialogConfirmed will remain false at all times. You can try this yourself.

      With regards to your pet-peeve, I am aware that setting false here is unnecessary, but it helps with readability (which I know you're against :P) in determining that it's a boolean value.

  4. this is awesome, have been looking for this for so long, thanks a ton!!

  5. I appreciate your attitude to help others. Thank you…

    I was looking for dynamically creating the dialog div, as well as allowing customization of the title and dialogText. I used your function ConfirmDialog(obj, title, dialogText) inside the script tag and
    the below code inside the body:

    and debug the application, clicked the button, nothing happens…

    Kindly help. I am desperately in need of this urgently…

    Thank you so much…

  6. The code is not shown in the above comment. This is the code i have written:

  7. Thank you Mark. Thank you soooooooooooooo much. Appreciate your help…

    Thanks,
    Shinezzz

  8. Great Mark!!! I just loved your coding. you made my job so easy. Thank you…
    But I need to have a control on my application so I would like to ask you something more.
    As I am calling the function in button click from the code behind using ScriptManager.RegisterStartupScript(), I want to return a variable when the ‘Yes’ button is clicked, the variable is set to true and the further action execution take place while if ‘No’ is clicked, the dialog box closes without the execution of further actions, So my question is how to access the variables and the buttons inside the jquery function in the code behind ( I mean in the aspx.cs). I hope u understood my problem. Pls help

    • Hi Anne,
      What I understood is that in the “Yes” function, you would like a variable value defined which may then be picked up from backend. Have you considered inserting the value into a Hidden Field before calling obj.click()? I believe this would resolve your issue.

  9. Thank you Mark for your prompt response.

    I tried doing this in the jquery function

    before calling obj.click(); I assigned the hidden field value as ‘yes’ using $(“input[id$=hdnValue]“)(“Yes”);
    and checked in the button click

    If hdnValue.Value = “Yes” Then
    ……..
    ……
    End If

    But this doesn’t work. I think the syntax of assigning and retrieving hidden field is not correct. Can you please help me to get the correct syntax. Thank you

  10. Thank you Mark. Thanks a lot.

  11. I have tried your syntax as well but doesn’t work. Please help.

  12. Hi Mark,
    I don’t think the hidden field will help me. I am trying to built an external .js file as I have to use this function in many places in my application. Basically, what i want to do is, as I am calling the confirmdialog function in the button_click, the action should trigger after pressing the yes button on the dialog box and while i press no button, the action should not trigger. So, could you please guide me with a proper solution to make this happen. Hope you understood my problem…

  13. Yeah!!! I know that. I guess i have not mentioned my problem exactly…
    Actually I am calling the function in the button click from the code behind using ScriptManager.RegisterStartupScript() and writing the action as well in the same button click, so obviously, the action will get triggered anyway but i want the action to get triggered only when i click the yes dialog button. Could you suggest any solution for this? Thank you…

  14. Hello,

    Thank you for this, but i’m getting tripped up on what is probably a small thing. It seems i’m getting tripped up by this on the button declaration:

    OnClientClick=”return confirmDialog(this);”

    I get an error, the program doesn’t seem to know what “this” is. I’m using your first implementation. The code is in a block on the page; i’ve tried it both inside and outside document.ready.

    Thanks for any help you can give!

    Rich Thomas

  15. Hi Mark
    I am trying to implement this. I have IE 8 browser.
    Even when I use you zip file example without any changes.
    I don’t see the message ‘Are you sure?’ I only see a scroll bar there.
    So without the message I really cant implement the confrim button.
    Any help would be appreciated.
    And can also give some exampel for
    1) Alert box
    2) Calling the jquery confrim box from code behind (Programatically)

    Regards

    • Default.aspx.
      Line 30.
      Change the height.

      • Thanks for your Super quick reply. yes I did that the only thing I did not do is press Ctrl + F5
        Which solove the problem.

        I have a different issue now It works absolutely fine when i have master (I have reference all the js and css file in the master page) and child page in the same root folder.

        But when I move the child page to differnt folder and when I click the button
        I get javascript object not found error. Other wise every is fine with my page.
        Should I have those javascript and css file in every fodler and point in child page?

        any help?

        • Nathan, the issues you are having are not related to this post.
          You do not have the correct path specified in the script reference as you are moving files around.
          Adjust the script and stylesheet references accordingly.
          For example, if you are putting the scripts into a folder named “Scripts” at the root of your website, the src would be “/Scripts/javascriptFile.js”.

          • I Really appreciate what you are saying. but as I said My master pages have allways been the same place (The root folder), which has all the links for the .js and .css files.
            It s the client page which moved form root to separate folder. the client does not have any links . but it implements the button action in the client page.So there is nothing to change in the client page.
            Rest of the modules on the client page works fine its only the dialog implementation which is the problem. As you said its some thing to do with where the client page is. But mu script files are in the same place and my reference to scripts are in the master pages which is untouched.

            Iam I presenting my self clear there?

            Plese let me know your thoughts.

            Nathan

          • Nathan, I would have to see the code as I’ve implemented this through the use of Master Pages countless times before and I’ve had no issue whatsoever.

  16. Hi Mark,
    found this solution the other day and it worked perfectly. Thanks for sharing it.
    Regards

  17. Perfect!!!!!!!!I solved my problem !!Thank you!!


Cancel reply

No trackbacks yet.