Search code examples
javascriptobserver-pattern

Observe fields on a form and report changes


Observe fields on a form and report changes

I have now written a simple utility (part of the observer pattern) to observe the changes made in each field of a form.

var idInt = setInterval(function() {
  // each input is a document.getElementById(id)
  var len = inputList.lenght;

  while(len--) {
    //send value to somewhere
    someWhere(ininputList[len].value);
  }
}, 40)

but i have issues like:

  1. when change the value with mouse (cut/paste)
  2. when change the value programmatically

the value take by someWhere(ininputList[len].value); dont refresh even I tried to add events (onchange, oncut, onpaste, oninput, onkeyup) to the elements to avoid setIntervalloop but with the events when i try to change programmatically the values dont fires.

which would be a better approach to observe changes in the values ​​of elements (input [button | text | password | url | email], radio, checkbox, select) taking into account that programmatic changes monitorizen and changes through the interface user,

Note: I am looking for a raw solution, no jquery, prototype, js class or any framework just native javascript


Solution

  • I am not sure what is the problem because below code works

    setInterval(function() {
      var inputList = document.getElementsByTagName('input')
      var len = inputList.length;
    
      while(len--) {
        console.log(inputList[len].value);
      }
    }, 4000)​
    

    It prints changed values every 4 secs, you can see it in action here http://jsfiddle.net/QKqzT/