最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Prevent losing form data by navigating away from page - Stack Overflow

programmeradmin0浏览0评论

I am creating a datagrid with hundreds of rows which contain a checkbox on each row so that the user can select an item from the grid.

Now the user may spend a great deal of time going filtering/searching through the grid and ticking the required checkboxes, only to accidentally press the backspace key on their keyboard or click on a hyperlink on the page. And they would lose all their checkbox selections.

So I want to introduce some functionality whereby if at least one checkbox has been ticked, then if the user unintentionally does an action that would navigate them away from the page, then a JavaScript confirm message is displayed to notify the user of this.

The checkboxes would all belong to the same group, for instance it would be called "products".

Is this possible to do at all?

I am creating a datagrid with hundreds of rows which contain a checkbox on each row so that the user can select an item from the grid.

Now the user may spend a great deal of time going filtering/searching through the grid and ticking the required checkboxes, only to accidentally press the backspace key on their keyboard or click on a hyperlink on the page. And they would lose all their checkbox selections.

So I want to introduce some functionality whereby if at least one checkbox has been ticked, then if the user unintentionally does an action that would navigate them away from the page, then a JavaScript confirm message is displayed to notify the user of this.

The checkboxes would all belong to the same group, for instance it would be called "products".

Is this possible to do at all?

Share Improve this question edited Jul 24, 2011 at 19:49 Tomas 59.6k54 gold badges249 silver badges382 bronze badges asked Jul 24, 2011 at 18:04 MAX POWERMAX POWER 5,45816 gold badges98 silver badges146 bronze badges 1
  • 1 Have you tried looking at HTML5's LocalStorage? – PhD Commented Jul 24, 2011 at 18:08
Add a ment  | 

1 Answer 1

Reset to default 11

There is a beforeunload event which occurs when the user navigates away: http://jsfiddle/FprNV/1/.

Returning a string there results in a message appearing with two buttons (stay/navigate); the exact implementation of this dialog differs across browsers.

$(window).bind('beforeunload', function() {
    var checkboxcount = $("input:checkbox:checked").length;
    if(checkboxcount > 0) {
        return 'Are you sure?';
    }
});
发布评论

评论列表(0)

  1. 暂无评论