Login

Confirm alert if the user navigates away without saving changes

Author:
mrazzari
Posted:
July 16, 2009
Language:
JavaScript
Version:
Not specified
Score:
0 (after 0 ratings)

A confirm alert is displayed if the user has made any changes to the form, and attempts to navigate away from the page without saving (click the back button, hit reload, click the breadcrumbs, logout, etc). Much like GMail's "Your message has not been sent. Discard your message?" prompt.

Uses the JavaScript helpers built into Django, without relying on 3rd party libs like jQuery. (There might be simpler options if you're already using jQuery or prototype).

To use this, simply create a custom admin template. For example at:

templates/admin/YOUR_APP_NAME/change_form.html

{% extends "admin/change_form.html" %}
{% block after_related_objects %}
{{ block.super}}
<script type="text/javascript">
... script goes here ...
</script>
{% endblock %}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
addEvent(window, "load", function(){
	var inputs = []
	inputs = inputs.concat(document.getElementsBySelector("input"));
	inputs = inputs.concat(document.getElementsBySelector("select"));
	inputs = inputs.concat(document.getElementsBySelector("textarea"));
	if (inputs.length > 0){
		for (var i=0, t=inputs.length; i<t ;i++){
			if (inputs[i].parentNode.className.indexOf('submit-row') == -1){
				addEvent(inputs[i], "change", function(){ window.onbeforeunload = function(){
					return "Your changes have not been saved.";
				}});
			} else {
				addEvent(inputs[i], "click", function(){ window.onbeforeunload = null });
			}
		}
	}
})

More like this

  1. Django Collapsed Stacked Inlines by applecat 1 year, 3 months ago
  2. Django Collapsed Stacked Inlines by mkarajohn 3 years, 5 months ago
  3. Dynamically adding forms to a formset. OOP version. by halfnibble 9 years, 1 month ago
  4. Convert multiple select for m2m to multiple checkboxes in django admin form by abidibo 11 years, 2 months ago
  5. Django admin inline ordering - javascript only implementation by ojhilt 11 years, 6 months ago

Comments

Please login first before commenting.