Colin
Colin

Reputation: 22595

How to prevent AutoPostBack when DropDownlist is selected using jQuery

I want to show a confirm dialog when the user selects an item in a DropDownList. If the user presses Cancel, I want to stop the postback. Here is the function I add to the onchange event:

function imitateConfirmUnload(event) {
    if (window.onbeforeunload = null)
        return true;

    return confirm("Are you sure you want to navigate away from this page?\n\nYou have unsaved changes\n\nPress OK to continue or Cancel to stay on the current page.");
}

And this is the relevant bit of code in my startup script to add the handler to the event:

function addConfirmToWarnClasses() {

    $('.warn').change(function() {
        imitateConfirmUnload()
    });
}

The problem is that the postback occurs even if the user selects Cancel. If I move the handler on to the click event, it works. But it feels clunky to me.

Edit

Correction: it doesn't work onclick, because the dialog prevents selection, so when the user selects OK, no change has taken place, and no postback when you want it!

Edit 2

The DropDownList is inside an UpdatePanel so that may affect behaviour.

Upvotes: 2

Views: 13707

Answers (4)

dnk.nitro
dnk.nitro

Reputation: 496

I know this question is kind of old, but since it popped up in google search when I needed an answer to it, I will post solution here. I think it is simplier than those posted before.

I took it from http://forums.asp.net/p/1475520/3432980.aspx:

<script type="text/javascript">
    function stopPostback()
    {
        if (blahblah)
            return true; // stop postback


        return false;
    }
</script>

<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" onchange="if (stopPostback()) return false;">

The key part here is the code within onchage: to cancel AutoPostBack it has to return something (doesn't matter if true or false) and to proceed with AutoPostBack it should not return anything.

Upvotes: 2

Homer
Homer

Reputation: 7806

After reading this solution, I just removed the AutoPostBack on my DropDownLists and used this because it was so simple:

$("#DropDownList1").change(function (e) {
    if ($(this).val() == "0") {
        //do nothing
    }
    else {
        //do postback
        setTimeout("__doPostBack('DropDownList1','')", 0);
    }
});

or if you have multiple DropDownLists you want to make AutoPostBack:

$("select").change(function (e) {
    if ($(this).val() == "0") {
        //do nothing
    }
    else {
        //do postback
        setTimeout("__doPostBack('" + this.id + "','')", 0);
    }
});

Upvotes: 5

Colin
Colin

Reputation: 22595

Sure enough, cancelling asynchronous postbacks from an Update Panel requires a different technique:

http://msdn.microsoft.com/en-us/magazine/cc163413.aspx

Prevent ASP.net __doPostback() from jQuery submit() within UpdatePanel

//Adds an event handler to confirm unsaved changes when an asynchronous postback is initialised by an UpdatePanel
function setConfirmAsyncPostBack() {

    if (typeof (Sys.WebForms) === "undefined" || typeof (Sys.WebForms.PageRequestManager) === "undefined")
        return;

    var prm = Sys.WebForms.PageRequestManager.getInstance();
    prm.add_initializeRequest(confirmAsyncPostBack);
}

//An event handler for asynchronous postbacks that confirms unsaved changes, cancelling the postback if they are not confirmed
//Adds the confirmation to elements that have a css class of "warn"
function confirmAsyncPostBack(sender, args) {
    if (window.onbeforeunload != null && args.get_postBackElement().className == "warn" && !unloadConfirmed())
        args.set_cancel(true);
}

//Displays a confirmation dialog that imitates the dialog displayed by onbeforeunload
function unloadConfirmed() {

    var confirmed = confirm("Are you sure you want to navigate away from this page?\n\n" + unloadMessage() + "\n\nPress OK to continue or Cancel to stay on the current page.");
    if (confirmed)
        window.onbeforeunload = null;
    return confirmed;
}

function unloadMessage() {

    return 'You have unsaved changes.';
}

This code goes with the problem described in my other question: DropDownList not firing onbeforeunload when AutoPostBack="True"

Upvotes: 0

Nick Craver
Nick Craver

Reputation: 630349

You need to return from that function as well, like this:

$('.warn').change(imitateConfirmUnload);

Currently the return value isn't being used. This would also work:

$('.warn').change(function() {
  return imitateConfirmUnload();
});

Also, I'm pretty sure you want an equals check here:

if (window.onbeforeunload == null)
    return true;

Currently it's nulling out the onbeforeunload handler if it was present.

Upvotes: 2

Related Questions