Reputation: 57
I am facing a problem with IE not Chrome. It does not trigger change event after I change the value by javascript. I think it work right as the specification of event change. When user change the input by javascript then lose focus on the input that means user does not(javascript does) change the input. But Chrome is smart guy he knows user did saw the change on input so he trigger change :). Is there anyway to make IE behaves like Chrome?
document.getElementById('inputName').addEventListener("keyup", function(e){
this.value += '_';
});
<body>
<input id="inputName" value="name" onchange="document.getElementById('outputName').innerHTML = document.getElementById('inputName').value"/>
<div id="outputName">name</div>
</body>
Upvotes: 0
Views: 3108
Reputation: 136796
It indeed seems weird that the change event gets overriden by this js action... I guess specs are relatively unclear on this point, so I'm not sure if we can call it a bug.
Anyway, you can mimick this behavior yourself by listening to the input event, which will trigger every time the user did commit changes to the input's value.
From there, you just need to raise a flag that you will read in the blur
event:
inp.oninput = function(e) { // every time the user commits a change
this._hasChanged = true; // raise a flag
};
inp.onblur = function(e) { // when we loose focus
if (this._hasChanged && // only if there were some changes made by the user
typeof this._onchange === 'function') {
this._onchange(); // trigger our fake change event
}
this._hasChanged = false; // set the flag back to false
};
inp._onchange = function(e) { // our fake onchange listener
log.textContent = this.value;
};
inp.onkeyup = function(e) {
this.value += '_';
}
<input id="inp" value="name">
<pre id="log"></pre>
Solution: https://jsfiddle.net/hrr3n0eh/
Upvotes: 1