Form Check Modified

Have you ever been on a website and filled out a form, only to accidentally refreshed or left the page without having saved your data. This can be a horrible experience to your users and they may leave your site without ever proceeding forward. Luckily, with a few sprinkles of some javascript, we can remedy this issue.

To get started, we’ll create a new rails application and a user scaffold.

We can then rename the app/assets/javascripts/users.coffee to users.js

Paste in the following into this file.

Or if you prefer coffeescript you can use this instead:

Notice that we are selecting the form via form[role="check-modified"] which means that we will need to modify our user’s form to include this role. This is a good way to prevent unwanted alerts on your application for things like search forms or other forms that will automatically save when fields are changed.

In our user’s form, we can add html: { role: 'check-modified' } which will trigger the javascript to check our forms for any unsaved changes.

Now, once we refresh our page, whenever we modify the form and try to leave without saving, we get an alert!