如果发生任何更改,如何设置退出弹出窗口并尝试移动到其他页面

时间:2016-01-06 05:49:07

标签: jquery

我已尝试过表格序列化并检查是否在点击“取消”按钮时进行了任何其他更改。现在我需要,即使发生任何导航,也会出现弹出窗口。

var global=$("#form").serialize();
function cancelfunction(){
    if(global!=$("#form").serialize()))
        {//popup triggers }}

谢谢

1 个答案:

答案 0 :(得分:0)

您可以创建一个布尔标志来指示是否有任何更改,并在每个输入类型更改时,将其触发为true,而在保存时将其设置为false。在页面卸载检查其值。

通常你会达到这样的目的:

alert('you have unsaved data!');

但是,浏览器会屏蔽beforeunload上的提醒,因此您需要这样做:

return 'you have unsaved data!';

JS Fiddle

<强> CODE:

// Initializing, this will set an initial value of false to the flag changeNoSave.
var changeNoSave;


// on change event of eachinput type we need to check on, we set the flag to true
// as change without submit has happened.
$('.checkMe').on('change', function() {
  changeNoSave = true;
});

$('#submitBtn').on('click', function(e) {
  //e.preventDefault() just for demo, not part of the solution
  e.preventDefault();
  
  //we set our flag to false again, as change has happened but saved upon form submit
  changeNoSave = false;
  console.log('you can leave the page safely');
});


$(window).on('beforeunload', function() {
  // on before unloading the page, we check ifchanges happend but not saved , or like
  // if changeNoSave = true, we alert by the return line
  if (changeNoSave) {
    return 'you have unsaved data!';
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<form>
  <input type="text" class="checkMe">
  <input type="text" class="checkMe">
  <input type="checkbox" id="chkbx" class="checkMe">
  <label for="chkbx">Test</label>
  <select class="checkMe">
    <option value="1">option 1</option>
    <option value="2">option 2</option>
    <option value="3">option 3</option>
  </select>
  <button id="submitBtn">submit</button>
</form>