Recently found a situation where a client was looking to ensure people didn't accidentally navigate away from a page when entering data on a website.
This isn't normally that difficult, except in this case we didn't control much of the page content (dynamically pulling content).
I came up with this approach in jQuery I thought it would be worth sharing. The approach is:
- bind all ":input" items with a onchange event (this will catch all form elements)
- onchange of an input add a marker css class to flag that it was modified
- bind to the form submit event, remove all markers on the form when submitted
- onbeforeunload look see if there are any markers on the page, if there is warn the user the data will be lost
This approach works with multiple forms on the page. Note the traditional javascript event use onbeforeunload - jQuery's beforeunload event will now allow the user to cancel unloading the page.
Next iteration of this type of approach will extend it to throw up an overlay with a listing of what form elements have data changes, and allow the user to post submits via ajax.
Here's the code:
<script type="text/javascript">
$(document).ready(function() {
$(':input').change(function() { $(this).addClass('elementHasChanged'); });
$("form").submit(function() {
//if the eventing item is part of a form, remove all the change flags from
$(this).children('.elementHasChanged:input').removeClass('elementHasChanged');
});
});
window.onbeforeunload = function() {
var changedCount = $('.elementHasChanged:input').length;
if (changedCount > 0) { return "Any changes you have made will be lost"; }
}
</script>
Update: Here's a working sample
No comments:
Post a Comment