Login

Confirm alert if the user navigates away without saving changes

Author:
mrazzari
Posted:
July 16, 2009
Language:
JavaScript
Version:
Not specified
Tags:
admin change-form
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. "Save and Continue" keyboard command for admin, with autoscroll by jcushman 5 years, 1 month ago
  2. Admin Input Field Character Count via jQuery by joshman 6 years, 2 months ago
  3. jQuery Double Click Edit ManyToMany in Admin by justhamade 5 years, 1 month ago
  4. Unobtrusvie Foldable Admin Interface by whiteinge 7 years, 1 month ago
  5. Add special field lookups to the Admin list_filter display by whiteinge 7 years ago

Comments

Please login first before commenting.