Detect programmatic changes on input type text [duplicate]

I find the simplest way is to actually trigger the event manually:

var evt = new CustomEvent('change');

Just listening to the change event is error-prone when the value is changed programmatically. But since you are changing the value, add two lines and fire the change event, with a CustomEvent.

then you’ll be able to catch this change event, either inline:

<input id="test" onchange="console.log(this)">

or with a listener:

document.getElementById('test').addEventListener('change',function(event) {

this have the advantage that if you have an input which can be changed by the user, you can catch both those events (from the user or the script)

this however depends on the fact that you are yourself programmatically changing the value of the input. If you are using libraries (such as datepickr) that change the values of your inputs you may have to get in the code and add those two lines at the right place.

Live Demo:

// input node reference
const inputElem = document.querySelector('input')

// bind "change" event listener
inputElem.addEventListener('change', e => console.log(

// programatically change the input's value every 1 second
setInterval(() => { 
  // generate random value
  inputElem.value = Math.random() * 100 | 0; 
  // simulate the "change" event
  var evt = new CustomEvent('change')
}, 1000);

Leave a Comment