开发者

The change event is not triggered before the beforeunloadhow

开发者 https://www.devze.com 2023-03-14 07:17 出处:网络
I know there are lots of questions about the \"beforeunload\" event and I think I read most of them. So I wrote the following code to warn a user about leaving a page before saving data, and it works

I know there are lots of questions about the "beforeunload" event and I think I read most of them. So I wrote the following code to warn a user about leaving a page before saving data, and it works most of the time.

It does not work when the user enters a value in input "f1" and leaves the page before tabbing out of the "f1". In that case the beforeunload event triggers before the change event and no warning is issued.

How should I modify the code?

thanks

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript">
var g_page_changed = false;
$(document).ready(function(){
    $(window).bind('beforeunload', function() { 
        if (g_page_changed) {
            return 'Do you really want to leave without saving?' ; 
        }
    });

    $('input').change(f开发者_JS百科unction() {
        g_page_changed = true;
    });
});
</script>
<form id="frm">
 <input id="f1" name="f1" type="text"/>
</form>


The change event isn't triggered until the input field has been blurd, so triggering a blur on your input before the conditional should fix it:

var g_page_changed = false;


$(window).bind('beforeunload', function() {
    $('input').blur();
        if (g_page_changed) {
            return 'Do you really want to leave without saving?' ;
        }
    });

  $('input').change(function() {
        g_page_changed = true;
    });

example: http://jsfiddle.net/niklasvh/XhT26/


MAybe you should use keypress() instead of change() and put some additional logic in it.

$('input').keypress(function() {
    var val = $(this).val();
    if (val.length > 0){
         g_page_changed = true;
    }else{
         g_page_changed = false;
    }
});

With this code you check if the lemgth of the input field is > 0 and then set the variable to true or otherwise (if the user cancelled all he entered) check it back to false. Look around for jquery plugins that check for 'dirtieness' of inputs if the input field has alredy some text in when the pages load.

The change event is triggered only when the input fields lose focus, i think.

0

精彩评论

暂无评论...
验证码 换一张
取 消