detect value change in input tag with vanilla javascript and MutationObserver

while true picture while true · Sep 3, 2015 · Viewed 18k times · Source

I want to detect when text/value change in input field. Even if I change the value with js, I want to detect that changes.

Here's what I've tried so far in demo in fiddle.

HTML:

<input type="text" id="exNumber"/>

JavaScript:

var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    // console.log('Mutation type: ' + mutation.type);
    if ( mutation.type == 'childList' ) {
      if (mutation.addedNodes.length >= 1) {
        if (mutation.addedNodes[0].nodeName != '#text') {
           // console.log('Added ' + mutation.addedNodes[0].tagName + ' tag.');
        }
      }
      else if (mutation.removedNodes.length >= 1) {
         // console.log('Removed ' + mutation.removedNodes[0].tagName + ' tag.')
      }
    }
     if (mutation.type == 'attributes') {
      console.log('Modified ' + mutation.attributeName + ' attribute.')
    }
  });   
});

var observerConfig = {
        attributes: true,
        childList: false,
        characterData: false
};

// Listen to all changes to body and child nodes
var targetNode = document.getElementById("exNumber");
observer.observe(targetNode, observerConfig);

Answer

David picture David · Sep 3, 2015

To understand what is going on is necessary to clear up the difference between attribute (content attribute) and property (IDL attribute). I won't expand on this as in SO there are already excellent answers covering the topic:

When you change the content of a input element, by typing in or by JS:

targetNode.value="foo";

the browser updates the value property but not the value attribute (which reflects the defaultValue property instead).

Then, if we look at the spec of MutationObserver, we will see that attributes is one of the object members that can be used. So if you explicitly set the value attribute:

targetNode.setAttribute("value", "foo");

MutationObserver will notify an attribute modification. But there is nothing like properties in the list of the spec: the value property can not be observed.

If you want to detect when an user alters the content of your input element, the input event is the most straightforward way. If you need to catch JS modifications, go for setInterval and compare the new value with the old one.

Check this SO question to know about different alternatives and its limitations.