Dirty Checks for HTML Forms

$.fn.extend({
    setDirty: function (dirty) {
        this.data("dirty", dirty);
    }
});
var $forms = $("form");
$forms.setDirty(false);
$forms.change(function () {
    $(this).setDirty(true);
});
$forms.submit(function () {
    $(this).setDirty(false);
});
$(window).on("beforeunload", function () {
    var filter = function () {
        var $this = $(this);
        return $this.data("dirty") && !$this.data("ignore-dirty");
    };
    if ($forms.filter(filter).length > 0) {
        return "This page may have unsaved changes.";
    }
});

Usage:

<form>
    <label>
        First name
        <input type="text" />
    </label>
    <label>
        Last name
        <input type="text" />
    </label>
    <button type="submit">Submit</button>
</form>
<form data-ignore-dirty="true">
    <label>
        Search
        <input type="text" />
    </label>
    <button type="submit">Go</button>
</form>

Leave a Reply

Your email address will not be published.