Alert user to unsaved changes on page before closing the page. Rails 6. Updated

441 Views Asked by At

Updated to use smarter implementation (or at least briefer). This will make most of the comments irrelevant, but thank you for those comments.

How to alert user to unsaved changes on page before closing the page. Rails 6.

AreYouSure added via yarn add areyousure.

Relevant in application.js

import 'jquery';
global.$ = global.jQuery = jQuery;
window.$ = window.jQuery = jQuery;
import 'areyousure/areyousure.js';

In /edit.html.erb, data-areyousure added to div surrounding form

<div class="row">
  <div class="col-md-6 col-md-offset-3" data-areyousure >
    <%= render 'form' %>
  </div>
</div>

This doesn't even allow any changes to the form. As soon as you click in the form the edit page updates to Are you sure? Yes | No. Not a popup.

Not seeing much activity on the github page.

Demo (link on github is dead). Tried dirtyforms too. Had other issues. Seems like I'm closer with AreYouSure

1

There are 1 best solutions below

3
Ryenski On

It looks like you are targeting the div container around your form, instead of the form itself. Try attaching areyousure to the form object:

<% provide(:title, 'Edit Person') %>
<h1>Edit: <%= @person.full_name %></h1>

<script>
  $(function() {
    $('#person_edit_form form').areyousure(
      {
        message: 'It looks like you have been editing something. '
               + 'If you leave before saving, your changes will be lost.'
      }
    );
  });
</script>

<div class="row">
  <div class="col-md-6 col-md-offset-3" id="person_edit_form">
    <!-- !render bookmark -->
    <%= render 'form' %>
  </div>
</div>