Forum Moderators: open

Message Too Old, No Replies

jQuery Javascript to Block Leaving Page Without Saving Form

Don't Lose Content of Form TextArea Accidentally

         

incrediBILL

4:41 am on Aug 5, 2015 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Since I just went thru this and didn't find any code that easily solved my problems to stop text typed in a form from being lost, thought I'd share this.

For HTML changes, all I did to the original form on WebmasterWorld was set the textarea to id="post" and add onsubmit="noWarn()" to the form, that's it.

Here's the javascript that names it work, the bind function is jQuery that goes inside the document ready.

var theform=1;
function noWarn() {
theform=0;
};

$(window).bind('beforeunload', function(e){
var count=$("#post").val().length;
if(count&&theform) return true;
else e=null;
});


Basically if anyone clicks any submit buttons or causes the form to be submitted, noWarn() gets called and disables the warning variable. Then the beforeunload routine counts the data in the textarea "post" and if both are > 0 it means there's text in the form and submit was not called, it's some other click on the page.

May not work for all your situations, but for WebmasterWorld some of the other off-the-shelf code I tried didn't work for whatever reason and this was so simple it couldn't fail.

Hope this helps someone!

Fotiman

5:20 pm on Aug 5, 2015 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



The jQuery "bind" method is an older method. As of jQuery version 1.7, it's recommended to use "on" instead of "bind". You're using 1.11.1 so you should use "on" instead.

robzilla

5:50 pm on Aug 5, 2015 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Great, but "true" is not a very helpful message :-)

incrediBILL

5:57 pm on Aug 19, 2015 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Great, but "true" is not a very helpful message :-)


You don't see that in firefox, but you do is MSIE

robzilla

7:31 pm on Aug 19, 2015 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I use Chrome :-)