11

I'm working on adapting an IE-specific website to other browsers. For example, onpropertychange has been used extensively, and I'm using MutationObserver to emulate that behavior.

However, I can't get MutationObserver to react on value changes to input=text fields, neither on programmatic changes nor user input.

Consider:

<input type="text" name="test1" id="test1" />

and

var config = { attributes: true, childList: true, characterData: true, subtree: true };
var observer = new MutationObserver(function() { alert('success'); } );
observer.observe(document.getElementById('test1'), config);

If I try to change the value by document.getElementById('test1').value = 'something' or keyboard input, nothing happens.

However, if I try to change something else about the element, for example its id or name (by JavaScript), the MutationObserver fires.

Value changes and MutationObserver work fine with other input types, event with the value of hidden fields.

This behavior is consistent across browsers.

Does anybody know how I can observe value changes on text fields? Or do I have to approach this differently?

tdrummdk
  • 151
  • 1
  • 5
  • 1
    For user-triggered changes, there's `change`. I assume you are primarily concerned about programmatic changes? – John Dvorak Oct 23 '13 at 12:03
  • 1
    Yes. But intrigued that even keyboard input doesn't work. – tdrummdk Oct 23 '13 at 12:06
  • 1
    It does not work because the `value` attribute does not get updated. Mutation Observers, sadly, only observe the physical DOM and not the virtual DOM. That is why `ele.onclick = function(){}` never triggers Mutation Observers. However, you can use [this horrible evil library](https://github.com/anonyco/IDL-Property-Observer) in order to force the attribute to be updated when the `value` property is set with your Javascript. After running the wretched library, the code above should work just as you hope it would. – Jack G Aug 19 '19 at 01:50

2 Answers2

11

The MutationObserve is used to listen for changes of DOM, but when you enter or delete some characters, you will see the attribute value has not been changed. like this:

name: <input type="text" id="name" value="ZJZHOME">

now we delete some characters, now the value is "ZJZHO":

var input = document.getElementById('name');
input.getAttributes('value') //alse "ZJZHOME"
input.value                  // now is "ZJZHO"

you can see that it didn't change the DOM when you delete characters, so, we should change the DOM...

I think we can solve this problem by following method:

input.oninput = function(e) {
    this.setAttribute('value', input.value)
}

now the mutation observers can observe changes in the form field's status.


I hope you can understand what I say..... My English is poor..........

ZJZHOME
  • 129
  • 1
  • 5
0

We can use jQuery onkey functions.

<input type="text" name="test1" id="test1" /><br>


 $("#test1").keydown(function(){
 console.log('pressed')
})