177

Is there a way I can create a constant function that listens to an input, so when that the 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 like, for example:

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
gespinha
  • 7,968
  • 16
  • 57
  • 91

11 Answers11

240

This is what events are for.

HTMLInputElementObject.addEventListener('input', function (evt) {
    something(this.value);
});
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • 79
    Would not work if input value is changed by javascript – ImShogun May 24 '17 at 12:37
  • 3
    Note that `typeof this.value` is `string`. If a number is needed, convert it with [parseInt](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt) or [parseFloat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseFloat). – Akseli Palén Nov 13 '19 at 18:53
  • 2
    In continuation to @ImShogun 's remark. Check [Azune-NK's answer](https://stackoverflow.com/a/62235852/9583480) to see how to trigger the event from JavaScript, if you change the value there. Super helpful. – s3c Apr 29 '21 at 09:18
  • 1
    @ImShogun This answer seems to be able to watch properties of elements such as value: https://stackoverflow.com/a/61975440/1764521 – Damien Golding Jun 11 '21 at 09:36
  • I used `window.addEventListener('input', function (evt) { if() {} })` – Leffa Apr 01 '22 at 13:51
  • You could use `this.valueAsNumber` for numbers – Falling10fruit Oct 04 '22 at 07:24
46

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/

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Niffler
  • 1,645
  • 11
  • 11
  • 30
    Would not work if input content is changed by javascript. neither with 'input' nor 'change' event. – ImShogun May 24 '17 at 12:37
  • 26
    What event can you listen to when the value is changed by javascript? – zero_cool Mar 06 '19 at 23:17
  • 8
    And as the others pointed out, doesn't trigger until you exit the input field either. Old answer by now, I know. But these answers pop up surprisingly often and they never mention the limitations. – Torxed Oct 02 '19 at 14:56
  • 2
    @ImShogun any ideas on how to "support" the case when the input is changed via JS? – Alessio Nov 13 '20 at 10:04
  • @ImShogun This answer seems to be able to watch properties of elements such as value: https://stackoverflow.com/a/61975440/1764521 – Damien Golding Jun 11 '21 at 09:35
19

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
});
AmerllicA
  • 29,059
  • 15
  • 130
  • 154
15

Default usage

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

But, if you want to fire event when you change inputs value manually via JavaScript you should use custom event (any name, like 'myEvent', 'ev', etc.). If you need to listen to forms 'change' or 'input' event and you change inputs value via JavaScript, you can name your custom event 'change' or '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(event);

Creating and triggering events

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Azune-NK
  • 159
  • 1
  • 2
  • 4
    This is it! Thank you. That `element.dispatchEvent(new Event('change'))` was key. Didn't make sense that event isn't triggered on manual JS change, but suddenly it does. Colour me stupid. – s3c Apr 29 '21 at 09:15
7

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

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

myInput.addEventListener("change", (e) => {
  // here we do something
});
Runsis
  • 831
  • 9
  • 19
3

HTML form input contain many events. Refer from HTMLElement, on the sidebar go to Events menu and expand it. You will see many useful events, such as beforeinput, change, copy, cut, input, paste, and drag drop events.

iput & change

The beforeinput, and input events are fired by order when you type the form input value.

When the form input value has changed and you lost focus on that input, the change event is fired.

Cut, copy, and paste

When you cut (CTRL + X on keyboard shortcut) the input value, the cut, beforeinput, input events are fired. When you copy (CTRL+C on keyboard shortcut), the copy event is fired alone.

When you paste the value from the clipboard (Ctrl + V on the keyboard shortcut), the paste, beforeinput, input events are fired.

JavaScript change value

To change the input value by JavaScript and make important events work, you need to dispatch at least two events by order. One is input and two is change. So that you can focus your code to listened to input or change event. It's easier this way.

Here is all the sample code.

(() => {
    let inputText = document.getElementById('text');
    let submitBtn = document.getElementById('submit');
    let triggerJSBtn = document.getElementById('button');

    submitBtn.addEventListener('click', (event) => {
        event.preventDefault(); // just prevent form submitted.
    });

    triggerJSBtn.addEventListener('click', (event) => {
        const thisTarget = event.target;
        event.preventDefault();
        inputText.value = thisTarget.innerText;
        inputText.dispatchEvent(new Event('input'));
        inputText.dispatchEvent(new Event('change'));
    });

    inputText.addEventListener('beforeinput', (event) => {
        const thisTarget = event.target;
        console.log('beforeinput event. (%s)', thisTarget.value);
    });

    inputText.addEventListener('input', (event) => {
        const thisTarget = event.target;
        console.log('input event. (%s)', thisTarget.value);
    });

    inputText.addEventListener('change', (event) => {
        const thisTarget = event.target;
        console.log('change event. (%s)', thisTarget.value);
    });

    inputText.addEventListener('cut', (event) => {
        const thisTarget = event.target;
        console.log('cut event. (%s)', thisTarget.value);
    });

    inputText.addEventListener('copy', (event) => {
        const thisTarget = event.target;
        console.log('copy event. (%s)', thisTarget.value);
    });

    inputText.addEventListener('paste', (event) => {
        const thisTarget = event.target;
        console.log('paste event. (%s)', thisTarget.value);
    });
})();
/* For beautification only */

code {
    color: rgb(200, 140, 50);
}

small {
    color: rgb(150, 150, 150);
}
<form id="form">
    <p>
        Text: <input id="text" type="text" name="text">
    </p>
    <p>
        Text 2: <input id="text2" type="text" name="text2"><br>
        <small>(For lost focus after modified first input text so the <code>change</code> event will be triggered.)</small>
    </p>
    <p>
        <button id="submit" type="submit">
            Submit
        </button>
        <button id="button" type="button">
            Trigger JS to set input value.
        </button>
    </p>
    <p>Press F12 to view results in your browser console.</p>
</form>

Please press F12 to open the browser's console and see the result there.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
vee
  • 4,506
  • 5
  • 44
  • 81
0

Each time a user inputs some value, do something.

var element = document.getElementById('input');
element.addEventListener('input', function() {
 // Do something 
});
UserName Name
  • 267
  • 2
  • 3
0

IMHO, it's just 'onchange' mistaken as 'oninput' which are two different things.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
-1

Keydown, keyup, and input are events that fire immediately when input changes.

I would use keydown or input events to get the changed value from the input box.

const myObject = document.getElementById('Your_element_id');
myObject.addEventListener('keydown', function (evt) {
// Your code goes here 
 console.log(myObject.value);
});
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Mitesh vaghela
  • 470
  • 4
  • 6
-3

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') 
})
Niso
  • 79
  • 10
-11

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...")
    })
});
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
kai
  • 1