javascriptjqueryjquery-dirtyforms

How to use jquery.dirtyforms?


I am getting confused on how to use jquery.dirtyforms.

I am trying to create a simple form with a text box and submit button. If the user modify the text box and try to refresh the page or click on a link inside the page before saving the result, Dirty Forms plugin should alert the user. But nothing is working.

Below is my code:

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="//cdn.jsdelivr.net/jquery.dirtyforms/2.0.0/jquery.dirtyforms.min.js" type="text/javascript"></script>
</head>

<body>
<script type="text/javascript">

    $(document).ready(function(){
            $('form').dirtyForms({ 
        dialog: { title: 'Wait!' }, 
        message: 'You forgot to save your details. If you leave now, they will be lost forever.' 
    });
    });

</script>
<form action="/" method="post">
        <input id="input" type="text" />
        <button id="btnSubmit" type="submit" value="Submit">Submit</button>
        </form>

<a href="http://www.google.com">google</a>
</body>
</html>

What is wrong with this code and how to use this plugin?


Solution

  • Your code will work if you remove the title and message from the dirtyforms call. As per the documentation:

    // Customize the title and message.
    // Note that title is not supported by browser dialogs, so you should 
    // only set it if you are using a custom dialog or dialog module.
    $('form').dirtyForms({ 
        dialog: { title: 'Wait!' }, 
        message: 'You forgot to save your details. If you leave now, they will be lost forever.' 
    });
    

    Because you are trying to use the default browser dialog, these extra attributes cause the dirtyform code to break.

    <html>
    <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
    <script src="http://cdn.jsdelivr.net/jquery.dirtyforms/2.0.0/jquery.dirtyforms.min.js" type="text/javascript"></script>
    </head>
    
    <body>
    <script type="text/javascript">
    
        $(document).ready(function(){
                $('form').dirtyForms();
        });
    
    </script>
    <form action="/" method="post">
            <input id="input" type="text" />
            <button id="btnSubmit" type="submit" value="Submit">Submit</button>
            </form>
    
    <a href="http://www.google.com">google</a>
    </body>
    </html>