Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3 form helper to prevent user from navigating away and losing changes?

Is there a Rails helper or a Rails way of preventing the user from leaving the current page if they're typed something into the form on the current page?

I'm trying to prevent people from losing data if they click a header link if they have unsaved changes in a form.

like image 885
Amy Avatar asked Feb 23 '11 07:02

Amy


1 Answers

Rails doesn't know about the state of a form until it is submitted, but you can add a pinch of javascript to help in that case.

$('#header > a').click(function(){
  $('input').each(function(i){
    if ( $(this).attr(value) != '' ) {
      if ( confirm('are you sure you want to leave this form unfinished?') != 'true' ) {
        alert('quitter!);
      }
    }
  });
});

edit: Okay, so that only handles header link clicking (like you specified in your question), here's a solution that uses onbeforeunload. Full page source because I tested it out to make sure I'm giving you something to build on:

<html>
  <head>
    <title>Foo</title>
    <script>
      window.onbeforeunload = function(){
        var inputs = document.getElementsByTagName('input');
        var unfinished = 'false';
        for (var i=0; i<inputs.length; ++i) {
          if ( inputs[i].value != '' ) {
            unfinished = 'true';
          }
        }
        if ( unfinished == 'true' ) {
          return 'Are you sure you want to leave?';
        }
      }
    </script>
  </head>
  <body>
    <form>
      <input name='foo'/>
      <input type='submit'/>
    </form>
    <a href='/'>Leave</a>
  </body>
</html>

Of course this isn't a Rails-specific helper, but you could write your own helper to spit out a script tag with something like this in it into your views. You'll probably also want to put form-specific checks in rather than just checking every input for emptyness. Every form I've ever made was a beautiful and unique snowflake in some form or another.

like image 108
Unixmonkey Avatar answered Sep 28 '22 07:09

Unixmonkey