jScript confirm on navigate away when fields are dirty, multibrowser implementation?
I've been trying to implement the jquery.safetynet plug-in but I've been having difficulties getting it to work with check boxes and across multiple browsers. (Read: It must be ie6 compatible)
I've decided to give up on this implementation even though I really like it.
Do you have a good r开发者_如何学Pythonecommendation for a dirty field check and prompt for: navigate away, refresh, browser close?
Thanks!
use window.onbeforeunload to be notified when the page unloads. To check if anything is dirty within a form, you can query for all input, selects and see if the values are different than when the page was loaded.
I copy pasted this from the web to check if any values in a form are modified
window.onbeforeunload = function(e) {
if (isFormModified(document.getElementById('form-id-goes-here'))) {
return e.returnValue = "You have unsaved data in your form";
}
}
function isFormModified(oForm)
{
var el, opt, hasDefault, i = 0, j;
while (el = oForm.elements[i++]) {
switch (el.type) {
case 'text' :
case 'textarea' :
case 'hidden' :
if (!/^\s*$/.test(el.value) && el.value != el.defaultValue) {
return true;
}
break;
case 'checkbox' :
case 'radio' :
if (el.checked != el.defaultChecked) {
return true;
}
break;
case 'select-one' :
case 'select-multiple' :
j = 0, hasDefault = false;
while (opt = el.options[j++]) {
if (opt.defaultSelected) {
hasDefault = true;
}
}
j = hasDefault ? 0 : 1;
while (opt = el.options[j++]) {
if (opt.selected != opt.defaultSelected) {
return true;
}
}
break;
}
}
return false;
}
精彩评论