How do I know that a form input has changed?

tkalve picture tkalve · Dec 30, 2010 · Viewed 26.4k times · Source

I have a form generated by <% Ajax.BeginForm() {} %> which contains a lot of inputs and texareas.

When an input value change, I need to know about it and mark the input and the form as "dirty". If the user tries to leave the page without saving, I will ask him or her to confirm abandoning changes.

Any suggestion to how this should be done?

Answer

Tom Brothers picture Tom Brothers · Dec 30, 2010

The html controls include a property that holds the original value. You could compare this value with the current value to see if there have been any changes.

function getHasChanges() {
    var hasChanges = false;

    $(":input:not(:button):not([type=hidden])").each(function () {
        if ((this.type == "text" || this.type == "textarea" || this.type == "hidden") && this.defaultValue != this.value) {
            hasChanges = true;
            return false;             }
        else {
            if ((this.type == "radio" || this.type == "checkbox") && this.defaultChecked != this.checked) {
                hasChanges = true;
                return false;                 }
            else {
                if ((this.type == "select-one" || this.type == "select-multiple")) {
                    for (var x = 0; x < this.length; x++) {
                        if (this.options[x].selected != this.options[x].defaultSelected) {
                            hasChanges = true;
                            return false;
                        }
                    }
                }
            }
        }
    });

    return hasChanges;
}

function acceptChanges() {
    $(":input:not(:button):not([type=hidden])").each(function () {
        if (this.type == "text" || this.type == "textarea" || this.type == "hidden") {
            this.defaultValue = this.value;
        }
        if (this.type == "radio" || this.type == "checkbox") {
            this.defaultChecked = this.checked;
        }
        if (this.type == "select-one" || this.type == "select-multiple") {
            for (var x = 0; x < this.length; x++) {
                this.options[x].defaultSelected = this.options[x].selected
            }
        }
    });
}