Categories

Meta

Stimulus.js Tutorial – Don’t Lose Unsaved Form Fields

Published May 9, 2018 by john

You may shudder remembering that long form you were once filling out, only to accidentally click a link, or refresh the page. You lost everything, all your unsaved form entries, and then you had to redo your work and fill out the form again.

Don’t let your customers fall into the same trap. There are a number of ways to prevent the browser from changing the page without a user’s consent. Malware sites sometimes abuse these features, but as long as you’re respectful, your customers will appreciate not losing their information.

How?

The browser fires off a event every time it’s about to change the current page called beforeunload that we’ll use to prevent losing an unsaved form. We’ll also listen for Turbolinks turbolinks:before-visit event for page transitions inside our app.

Getting Started

HTML

Let’s add the Stimulus annotations to our form. The <form> tag is going to have the controller, and the window event listening actions. Each of the form inputs will have an action for when their value changes. The form will also have a data attribute called changed that we’ll update as data is entered into the form, which will be used to decide whether to stop the browser from leaving our page. The form’s submit button will have the final action that we’ll use to hijack the form submission, and stop the browser from preventing the form submission by resetting the changed to false.

I’m working with a simple ActiveRecord Post model which has a title, author, and text.

Stimulus Controller

Our controller has the three actions, and uses a changed data attribute to keep track of whether to prevent the browser from changing the page.

The changed attribute always starts at false. Every time our input field’s value changes, Stimulus calls the formIsChanged( event ) method, and the unsaved changes controller updates changed to true. In order for the form submission to work, the controller reverts changed to false to prevent the leavingPage( event ) function from displaying the leaving page popup and stopping the form submission.

Every time the browser attempts to leave the page, either with a beforeunload event or a turbolinks:before-visit event, the unsaved changes controller checks to see if the form has changed. If changed is false, it allows the browser to change page. If changed is true, then the controller prevents the page from changing. The turbolinks:before-visit uses a confirm message to make sure the user want’s to leave the page. The beforeunload event uses the browser’s native alert to make sure that the user wants to leave the page.