我有以下django形式:
<form class="form-inline" method = "post" >
{% csrf_token %}
{{ form.media }}
{{ form.as_p }}
<button type="submit" onclick="setFormSubmitting()">Submit</button>
</form>
和以下javascript
var isDirty = function() { return false; }
var formSubmitting = false;
var setFormSubmitting = function() { formSubmitting = true; };
window.onload = function() {
window.addEventListener("beforeunload", function (e) {
if (formSubmitting) {
return undefined;
}
var confirmationMessage = 'It looks like you have been editing something. '
+ 'If you leave before saving, your changes will be lost.';
(e || window.event).returnValue = confirmationMessage; //Gecko + IE
return confirmationMessage; //Gecko + Webkit, Safari, Chrome etc.
});
};
目标是:用户可以在没有任何警告的情况下离开,除非,在文本区域(form.media)中写入了某些内容,并且未单击提交(如用户键入了一些内容并将其移至另一页)。
我的挣扎在于“ isDirty”部分-如何检查是否在form.media中编写了某些内容。
编辑: Javascript问题已根据CodeCaster的answer得到修复(感谢Shafikur Rahman指出)