Reputation: 12341
I'm adding a mechanism in my website that's supposed to warn users whenever they are about to close a page they were working in. I'm binding a function dropDraftConfirmation
to the window.onbeforeunload
event, like this:
window.onbeforeunload = dropDraftConfirmation;
function dropDraftConfirmation()
{
if (<there is an input or textarea element not empty on the page>) {
alert('Your changes will be lost. Are you sure you want to exit the page?');
}
}
But this is called every time I close a page. So my question is, how to detect if there is an input or textarea element in the page that is not empty? I'm using jQuery by the way.
Upvotes: 0
Views: 782
Reputation: 1610
Your condition will look like this:
if ($("input[value!='']").length > 0 || $('textarea:not(:empty)').length > 0 ){
Upvotes: 0
Reputation: 100175
you could also do something like:
var errors = 0;
$("input, textarea").map(function(){
var val = $.trim( $(this).val() );
if( val.length < 1 ) {
errors++;
}
});
if( errors > 0 ) {
alert('Your changes will be lost. Are you sure you want to exit the page?');
}
Upvotes: 0
Reputation: 12796
I think this should do the trick.
window.onbeforeunload = dropDraftConfirmation;
function dropDraftConfirmation()
{
if ($("input:empty,textarea:empty").length == 0) {
alert('Your changes will be lost. Are you sure you want to exit the page?');
}
}
Upvotes: 2
Reputation: 3498
rewrite your function like the one below to check any unsaved changes before unload
window.onbeforeunload = checkUnSaved;
function checkUnSaved(){
if($("#textarea").val() === ""){
dropDraftConfirmation();
}else
return;
}
function dropDraftConfirmation()
{
if (<there is an input or textarea element not empty on the page>) {
alert('Your changes will be lost. Are you sure you want to exit the page?');
}
}
Upvotes: 0