Ask before reloading / changing page

3

I mean confirm if you are sure to leave the current page

I have a form, and I want to ask if the form has a filled field if you are sure to reload / exit the page

I'm currently using

window.onbeforeunload = function(e) {
    return "You have some unsaved changes";
};

but that works although I do not have any fields filled

    
asked by hubman 14.03.2018 в 16:06
source

2 answers

2

You will have to check, before showing the message, whether or not there has been a change in the form. The controls of the form have a property (that depends on the type of control) in which the initial value that they had when generating the page is saved.

Based on that you can do a generic function:

function formIsDirty(form) {
for (var i = 0; i < form.elements.length; i++) {
var element = form.elements[i];
var type = element.type;
if (type == "checkbox" || type == "radio") {
  if (element.checked != element.defaultChecked) {
    return true;
  }
}
else if (type == "hidden" || type == "password" ||
         type == "text" || type == "textarea") {
  if (element.value != element.defaultValue) {
    return true;
  }
}
else if (type == "select-one" || type == "select-multiple") {
  for (var j = 0; j < element.options.length; j++) {
    if (element.options[j].selected !=
        element.options[j].defaultSelected) {
      return true;
    }
  }
}
}
 return false;
}

And in the beforeunload :

window.onbeforeunload = function(e) {
e = e || window.event;  
if (formIsDirty(document.forms["tu_formulario"])) {
// For IE and Firefox
if (e) {
  e.returnValue = "You have unsaved changes.";
}
// For Safari
return "You have unsaved changes.";
}
};
    
answered by 14.03.2018 в 16:31
1

Look at this is a sweet alert as an example so you can use it.

$('button').click(function(){

  swal({
    title: "Aviso",
    text: "Esta seguro que desea salir?",
    type: "warning",
    showCancelButton: true,
    confirmButtonClass: "btn-danger",
    confirmButtonText: "Salir",
    cancelButtonText: "Cancelar",
    closeOnConfirm: false,
    closeOnCancel: false
  },
  function(isConfirm) {
    if (isConfirm) {
      location.href ="http://www.pagina1.com";
    } else {
      swal("Cancelado", "Usted esta aqui", "error");
    }
  });

  });
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.min.css" media="screen" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.min.js"></script>

<button>Irse</button>

Something like this occurs to me, Put in full screen, so you can see how it looks. I hope it works for you. Greetings!

    
answered by 14.03.2018 в 16:20