Prompting user to save when they leave a page

前端 未结 3 2008
自闭症患者
自闭症患者 2020-12-28 19:21

I need to prompt a user to save their work when they leave a page. I\'ve tried onbeforeunload but I need to show a styled prompt not the usual dialog box. Facebook has manag

3条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-28 20:02

    to improve on the answers of the others here I developed a great little script.

        $('.measurement_value').change(function() {
            $(window).bind('beforeunload', function(){
                return 'You have unsaved changes, are you sure you want to leave?';
            });
    
            $('#MeasurementAdminEditForm').submit(function(){
                $(window).unbind('beforeunload');
            });
            $('#CancelButton').click(function(){
                $(window).unbind('beforeunload');
            });
        });
    

    On each of my form elements I give a class of 'measurement_value' and then only load the beforeunload if one of those elements change. Furthermore I unload the beforeunload on submit of my form and on the click of the cancel button.

    hope this helps someone else.

提交回复
热议问题