How to show the “Are you sure you want to navigate away from this page?” when changes committed?

前端 未结 17 1595
深忆病人
深忆病人 2020-11-22 02:11

Here in stackoverflow, if you started to make changes then you attempt to navigate away from the page, a javascript confirm button shows up and asks: \"Are you sure you want

17条回答
  •  北恋
    北恋 (楼主)
    2020-11-22 02:55

    Based on all the answers on this thread, I wrote the following code and it worked for me.

    If you have only some input/textarea tags which requires an onunload event to be checked, you can assign HTML5 data-attributes as data-onunload="true"

    for eg.

    
    
    

    and the Javascript (jQuery) can look like this :

    $(document).ready(function(){
        window.onbeforeunload = function(e) {
            var returnFlag = false;
            $('textarea, input').each(function(){
                if($(this).attr('data-onunload') == 'true' && $(this).val() != '')
                    returnFlag = true;
            });
    
            if(returnFlag)
                return "Sure you want to leave?";   
        };
    });
    

提交回复
热议问题