警报未保存的表单更改 [英] Alert for unsaved changes in form

查看:362
本文介绍了警报未保存的表单更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在主文件中编写Jquery代码,因此如果用户更改了页面并且有任何未保存的更改,则用户应该获得警报。
我得到了一个答案:链接

I want to write Jquery code in master file, so that if there if user changes page and there is any unsaved changes user should get alert. I got one answer from this: link

然而,在大多数解决方案中,我将不得不在所有页面上编写代码。我希望它只在一个地方写,这样每个人都不必担心在模块中写它。我的代码如下:

However in most solution I will have to write code on all pages. I want it to write only at one place so that everybody dont have to worry to write it in their modules. My code is like:

<script type="text/javascript">
    var isChange;
    $(document).ready(function () {
        $("input[type='text']").change(function () {
            isChange = true;
        })
    });
    $(window).unload(function () {
        if (isChange) {
            alert('Handler for .unload() called.');
        }
    });

</script>

但每次我在文本框中进行更改.change()事件都没有触发。

But everytime i make changes in text boxes .change() event is not firing.

代码中可能出现什么问题?

What can be wrong in the code?

编辑:
我将.change()改为.click和它被解雇了。我正在使用jquery 1.4.1 ..是因为jquery版本,change()不起作用?

I changed .change() to .click and it is fired. i am using jquery 1.4.1..is it because of jquery version that change() is not working?

推荐答案

这就是我正在使用的,将所有这些代码放在一个单独的JS文件中并将其加载到头文件中,这样您就不需要一次又一次地复制它:

var unsaved = false;

$(":input").change(function(){ //triggers change in all input fields including text type
    unsaved = true;
});

function unloadPage(){ 
    if(unsaved){
        return "You have unsaved changes on this page. Do you want to leave this page and discard your changes or stay on this page?";
    }
}

window.onbeforeunload = unloadPage;

编辑未找到$:

此错误只能由以下三种情况之一引起:

This error can only be caused by one of three things:



  1. 您的JavaScript文件没有正确加载到你的页面中

  2. 你有一个拙劣的jQuery版本。这可能是因为有人编辑了核心文件,或者插件可能覆盖了$
    变量。

  3. 您在页面完全加载之前运行了JavaScript,因此,在jQuery完全加载之前。


确保所有JS代码都放在这里:

Make sure all JS code is being placed in this:

$(document).ready(function () {
  //place above code here
});

编辑保存/发送/提交按钮例外

$('#save').click(function() {
    unsaved = false;
});

编辑以使用动态输入

// Another way to bind the event
$(window).bind('beforeunload', function() {
    if(unsaved){
        return "You have unsaved changes on this page. Do you want to leave this page and discard your changes or stay on this page?";
    }
});

// Monitor dynamic inputs
$(document).on('change', ':input', function(){ //triggers change in all input fields including text type
    unsaved = true;
});

在alert_unsaved_changes.js文件中添加以上代码。

Add the above code in your alert_unsaved_changes.js file.

希望这会有所帮助。

这篇关于警报未保存的表单更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆