简体   繁体   中英

Add onclientclick confirmation to asp.net button only if condition is true?

I have a jQuery function set a hidden field value when changes are made to a textbox in an editable GridView. There are two buttons on the form; one to save changes and another to use the new values to execute a different process. I would like a confirmation to appear if the second button is pressed first, telling the user that the changes were not saved. Clicking "Yes" will save the changes and run the process for that button. Click "No" does nothing. I cannot use "return confirm('')" because that would show a confirmation all the time, even if not changes are detected. The confirmation should only show up if the hidden field has a value (in this case, "changed"). I've tried various solutions but get errors about functions not existing or other null objects.

The following detects changes and sets the hidden field value to "changed":

$(function () {
    $(".gv input.CAIFormat").bind('blur', function (e) {
         $(this).val(CommaFormatted($(this).val()));
         var change = $get('ctl00_BodyContentPlaceHolder_TabContainer1_tabSpaceDriver_hidSummaryTableChanged');
         change.value = "changed";
    });
});

The asp.net button should show a confirmation if the hidden field has a value:

<asp:Button ID="btnSaveSDDepartmet" runat="server" Text="Update Departments" />

Bind an event to the button with jQuery, check the value, then check the value of the input.

FYI -- start using on to bind events, bind is deprecated as of jQuery 1.7 (see http://api.jquery.com/bind/ )

$("btnSaveSDDepartmet").on('click', function (e) {
     var change = $get('ctl00_BodyContentPlaceHolder_TabContainer1_tabSpaceDriver_hidSummaryTableChanged');
     if (change.value == "changed") {
         if (!window.confirm("Changes not saved -- continue?")){
             e.preventDefault();
             return false;
         }
     }
});

Documentation * jQuery.on - http://api.jquery.com/on/ * window.confirm - https://developer.mozilla.org/en-US/docs/DOM/window.confirm

The following worked:

<asp:Button ID="btnSaveSDDepartmet" runat="server" Text="Update Departments" CssClass="CAIButton" OnClick="btnSaveSDDepartmet_Click" OnClientClick="if (!ConfirmMsg()) { return false; }" />

        function ConfirmMsg() {
        var obj = $get('ctl00_BodyContentPlaceHolder_TabContainer1_tabSpaceDriver_hidSummaryTableChanged');
        if (obj.value == "changed")
            return confirm("Data has been changed, but not saved. Do you want to save and continue?");
        else
            return false;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM