onClick Event and Javascript Confirm() to Control Postback That Works in All Browsers (that I tested)

Ok, using an onClick event to call a function which uses a confirm() alert to control posting a form has been around for a long time.  Something similar to this:

<input name=’submit’ type=’submit’ value=’Delete’ onClick=’return confdel();’>

One bug that was plaguing us for some time and due to low usage/priority had not been addressed, was that on many of the forms when a user selected Cancel to halt the submit the form was still posting! It was only in Internet Explorer (IE) that showed this bug – Firefox would correctly halt the form.

Long overdue to be corrected and the fix seemed to be elusive. But after numerous Google searches and reading other posts about similar issues and possible solutions I pieced together a fairly straightforward fix that seems to work correctly in browser: FF 4.0, IE8/9, Chrome.  Code sample is just for a simple confirm true/false: 

/* confirm delete */
function confdelappt() { 
        var msg = "\nYou have requested to delete this thing. By deleting this thing you will actually delete it. Are you sure?\n";
        if (confirm(msg)){
            return true;
                    if (window.event) { //will be true with IE, false with other browsers
                    window.event.returnValue=false; } //IE specific, seems to work
                else {
                    return false; } 

I found (with the help of other posts) that setting “window.event.returnValue=false;” would get IE the recognize that the onClick= event had returned false to then halt processing of the form submit. You could also include similar code for the “true” case but even if IE doesn’t see that the return is “true” the form still submits. Its usually the “false” case that matters most.

Definitely needed is the check that (window.event) is something otherwise the “window.event.returnValue=false;” code will error in browsers like Firefox – when it errors your form most likely will continue processing.

4 thoughts on “onClick Event and Javascript Confirm() to Control Postback That Works in All Browsers (that I tested)”

  1. @Drew – It does work ok from me in Chrome and without any added details hard to say why its not working as expected for you. The code is pretty simple and the IE check isn’t always needed – we found that it usually was necessary on older pages in our applications that required the browsers to be running in Quirks mode. On pages that were in Standards mode the extra IE check wasn’t always needed. But the code works either way so we use this type of javascript confirmation alert on any of the pages that need it.

  2. Very usefull post. I have wasted nearly 2 days to fix this issue. Thanks for your valuable post David Grayston

Comments are closed.