Emit JS Event when data automatically added in input

Topics related to client-side programming language.
Post questions and answers about JavaScript, Ajax, or jQuery codes and scripts.
Marius
Posts: 107

Emit JS Event when data automatically added in input

Hello
I have a JavaScript code that automatically adds some value in an input field.
How can I detect when the value was added in input?
If I use the 'change' event, it works when the users adds manually text in input, but not when it is added automatically with JavaScript.
Here is the script:

Code: Select all

<input type='text' name='inp1' id='inp1' />
<script>
inp1 = document.getElementById('inp1');

//register change event to #inp1
inp1.addEventListener('change', (e)=>{
  alert(e.target.value);
});

//automatically add some value in #inp1 after 2 sec.
window.setTimeout(()=>{
  inp1.value ='Be Happy';
}, 2000);
</script>

Admin Posts: 805
Hello,
For input fields it is better to use the 'input' event.
To emit and detect an event when some data is added automatically in input field, create an Event object with the event you want (input, change), then, apply the dispatchEvent() method to emit that event.
- Example with your script:

Code: Select all

<input type='text' name='inp1' id='inp1' />
<script>
inp1 = document.getElementById('inp1');

//register input event to #inp1
inp1.addEventListener('input', (e)=>{
  alert(e.target.value);
});

//create Event object with 'input' to automatically dispatch it when it's necessary
var ev_inp = new Event('input');

//automatically add some value in #inp1 after 2 sec., and dispatch the input event
window.setTimeout(()=>{
  inp1.value ='Be Happy';
  inp1.dispatchEvent(ev_inp);
}, 2000);

//The input event will be automatically detected whet setTimeout() dispatch the input

</script>