[javascript] Pure Javascript listen to input value change

Is there any way I can create a constant function that listens to an input, so when that input value changes, something is triggered immediately?

I am looking for something using pure javascript, no plugins, no frameworks and I can't edit the HTML.

Something, for example:

When I change the value in the input MyObject, this function runs.

Any help?

This question is related to javascript

The answer is


Default usage

el.addEventListener('input', function () {
    fn();
});

But, if you want to fire event when you change inputs value manualy via JS you should use custom event(any name, like 'myEvent' \ 'ev' etc.) IF you need to listen forms 'change' or 'input' event and you change inputs value via JS - you can name your custom event 'change' \ 'input' and it will work too.

var event = new Event('input');
el.addEventListener('input', function () { 
  fn();
});
form.addEventListener('input', function () { 
  anotherFn();
});


el.value = 'something';
el.dispatchEvent(input);

https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events


Actually, the ticked answer is exactly right, but the answer can be in ES6 shape:

HTMLInputElementObject.oninput = () => {
  console.log('run'); // Do something
}

Or can be written like below:

HTMLInputElementObject.addEventListener('input', (evt) => {
  console.log('run'); // Do something
});

Another approach in 2020 could be using document.querySelector():

const myInput = document.querySelector('input[name="exampleInput"]');

myInput.addEventListener("change", (e) => {
  // here we do something
});

If you would like to monitor the changes each time there is a keystroke on the keyboard.

const textarea = document.querySelector(`#string`)
textarea.addEventListener("keydown", (e) =>{
   console.log('test') 
})

instead of id use title to identify your element and write the code as below.

$(document).ready(()=>{

 $("input[title='MyObject']").change(()=>{
        console.log("Field has been changed...")
    })  
});

As a basic example...

HTML:

<input type="text" name="Thing" value="" />

Script:

/* event listener */
document.getElementsByName("Thing")[0].addEventListener('change', doThing);

/* function */
function doThing(){
   alert('Horray! Someone wrote "' + this.value + '"!');
}

Here's a fiddle: http://jsfiddle.net/Niffler/514gg4tk/