开发者

How to detect textarea or input type="text" editing?

I use this snippet to prevent the us开发者_C百科er from accidentally navigating away from the editing page:

var warning = false;
window.onbeforeunload = function() {
  if (warning) {
    return '';
  }
}

Now I want to set the variable warning to be true if any of the textarea or input type="text" has been modified, I want to use the onkeyup event such as in:

document.getElementById('textarea_id').onkeyup = function() {
    warning = true;
}

But it's not working. Don't quite want to use jQuery on this. Any insights?

Update:

Changed to this:

var warning = false;
window.onbeforeunload = function() { 
  if (warning) {
    return 'You have unsaved changes.';
  }
}
document.getElementById('textarea_id').onkeyup = function() {
    warning = true;
}

Yet it's still not working.

By the way, it's put in in the of the page. There are no javascript anywhere else.


The return value of the onbeforeunload event is only used if it isn't equivalent to false.

Change return ''; to

return 'You have unsaved changes.';
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜