Question

 $(function(){
   var a=document.getElementById('text_editor_textarea'),regEx=/^\s*$/,
 updateOrig = function() {
       var sc = $(a).data('sceditor');
         if(sc){
         sc.bind('keypress', sc.updateOriginal);
         sc.blur(sc.updateOriginal);
   }else {
     setTimeout(updateOrig , 200);
   }
 };
 updateOrig();  
 if(a.value !== "" && regEx.test(a.value) ){
       window.onbeforeunload = function(){
         return "You have a post waiting to be submitted";
      };
  }
});

This code should check if there is data in a and if there is onbeforeunload the alert should be prompted. It works except that even if there is no data in the textarea it still is prompted. Am I doing something wrong here?

Was it helpful?

Solution

Just do a.value !== "" instead of a.value !== null || a.value !== "" inside of this if block:

if (a.value !== null || a.value !== "") {
    window.onbeforeunload = function () {
        return "You have a post waiting to be submitted";
    };
}

Also, flip the if and the event function assignment to this:

window.onbeforeunload = function () {
    if (a.value !== "") {
        return "You have a post waiting to be submitted";
    }
};

I didn't realize this before, but only on page load would your message get called since otherwise the assignment wouldn't occur since the textarea would be empty when you first opened the page.

jsFiddle

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top