Find out if html form has changed

前端 未结 6 2173
清酒与你
清酒与你 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:00

    This is easily achieved in JavaScript without jQuery. initChangeDetection() can be called multiple times:

    function initChangeDetection(form) {
      Array.from(form).forEach(el => el.dataset.origValue = el.value);
    }
    function formHasChanges(form) {
      return Array.from(form).some(el => 'origValue' in el.dataset && el.dataset.origValue !== el.value);
    }
    

    Test on JS Bin


    For older browsers that don't support newer arrow/array functions:

    function initChangeDetection(form) {
      for (var i=0; i

提交回复
热议问题