0

My question is a continuation of this post https://stackoverflow.com/questions/22438863/javascript-jquery-for-before-leaving-the-page?noredirect=1#comment34138272_22438863, it's a new function.

Am looking for below function:

In stackoverflow, if you type some answers and if you try to close that tab it will ask for confirmation message..

Below is my Html part:

<form id="demo">
 <input type="text" id="name" name=""/>
 <input type="email" id="emails" name=""/>
 <input type="number" id="ph" name=""/>
 <select name="" id="sample">
  <option>Select</option>  
  <option value="1">Chennai</option>
  <option value="2">Hyderabad</option>
 </select>
</form>

If user enters something and he clicks on logo to navigate away it asks for confirm message..its natural right???Even stackoerflow has this function..I tried this code but didn't worked

var changesMade = false;

function onDataChanged() {
 changesMade = true;
}

$('input:text, textarea, select').change(onDataChanged);
$('input:checkbox, input:radio').click(onDataChanged);

$("#homeicon").click(function() {
 if (changesMade) {
    return 'Changes have been made. Are you sure you want to leave the page?';
    location.href = "home.html";
 } else {
    return null;
 }
});
Community
  • 1
  • 1
user3408415
  • 1
  • 1
  • 5
  • shouldn't it be `$('input:text, textarea, select').click(onDataChanged);` instead of `$('input:text, textarea, select').change(onDataChanged);` – sshashank124 Mar 17 '14 at 02:52
  • possible duplicate of [javascript before leaving the page](http://stackoverflow.com/questions/7080269/javascript-before-leaving-the-page) – Ekusu Mar 17 '14 at 02:57
  • why are you duplicating your question again I would say it was already answerd... – Ekusu Mar 17 '14 at 03:02
  • @ Ekusu no its not answered chck the comment section fully – user3408415 Mar 17 '14 at 03:05
  • well then you should check the question your first question was a duplicate of since it already answers everything in my opinion and regarding the redirecting to another page it's also answered there – Ekusu Mar 17 '14 at 03:41

1 Answers1

4

You are looking for onbeforeunload or beforeunload in jQuery.

check here as well as googling for other places with that term.

Community
  • 1
  • 1
Mark Kasson
  • 1,600
  • 1
  • 15
  • 28