Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent losing form data by navigating away from page

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?

like image 833
MAX POWER Avatar asked Jul 24 '11 18:07

MAX POWER


1 Answers

There is a beforeunload event which occurs when the user navigates away: http://jsfiddle.net/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?';
    }
});
like image 83
pimvdb Avatar answered Oct 21 '22 18:10

pimvdb