How to use jquery.dirtyforms?

3.2k Views Asked by At

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?

2

There are 2 best solutions below

1
Joffutt4 On BEST ANSWER

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>

0
NightOwl888 On

While @Joffutt came up with a working solution, there is an explanation for this behavior that he overlooked. The issue is that you are setting a dialog module here:

dialog: { title: 'Wait!' },

This tells Dirty Forms not use the default browser dialog and to use your custom dialog module. However, you did not complete the rest of the custom dialog module registration as per the documentation (namely, you don't have an open method defined), so you have an invalid configuration.

If you don't want a custom dialog module, you should not define a dialog: in your configuration.