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 so
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...")
})
});
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
This is what events are for.
HTMLInputElementObject.addEventListener('input', function (evt) {
something(this.value);
});
Another approach in 2020 could be using document.querySelector()
:
const myInput = document.querySelector('input[name="exampleInput"]');
myInput.addEventListener("change", (e) => {
// here we do something
});
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
});
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/