How do I know that a form input has changed?

后端 未结 5 445
温柔的废话
温柔的废话 2021-02-04 00:59

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

5条回答
  •  無奈伤痛
    2021-02-04 01:56

    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
                }
            }
        });
    }
    

提交回复
热议问题