Find out if html form has changed

前端 未结 6 2197
清酒与你
清酒与你 2020-12-08 11:53

Using jquery I\'ve added a change handler to a form. This works when any input is changed BUT only if the user manually changes an input and not when some other code changes

6条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-08 12:19

    Serializing the form is certainly an option, but it will not work if:

    • you want to know which fields have changed
    • it only needs to check a subset of the fields
    • dynamically adding or removing fields.

    Fortunately, every form element has a default value associated with its object:

    • input, textarea : defaultValue
    • checkbox, radio : defaultChecked
    • select: defaultSelected

    for ex: to ckeck if input or textarea has changed:

    var changed = false;
    $(":text,textarea").each(function(){
        changed = this.value != this.defaultValue;
        return !changed; // return if at least one control has changed value
    });
    

提交回复
热议问题