200

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.

11 Answers 11

268

This is what events are for.

HTMLInputElementObject.addEventListener('input', function (evt) {
    something(this.value);
});
Sign up to request clarification or add additional context in comments.

7 Comments

Would not work if input value is changed by javascript
Note that typeof this.value is string. If a number is needed, convert it with parseInt or parseFloat.
In continuation to @ImShogun 's remark. Check Azune-NK's answer to see how to trigger the event from JavaScript, if you change the value there. Super helpful.
@ImShogun This answer seems to be able to watch properties of elements such as value: stackoverflow.com/a/61975440/1764521
I used window.addEventListener('input', function (evt) { if() {} })
|
50

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/

6 Comments

Would not work if input content is changed by javascript. neither with 'input' nor 'change' event.
What event can you listen to when the value is changed by javascript?
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.
@ImShogun any ideas on how to "support" the case when the input is changed via JS?
@ImShogun This answer seems to be able to watch properties of elements such as value: stackoverflow.com/a/61975440/1764521
|
23

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

1 Comment

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.
20

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
});

Comments

5

Another approach could be using document.querySelector():

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

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

Comments

5

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.

input & 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.

Comments

0

Each time a user inputs some value, do something.

var element = document.getElementById('input');
element.addEventListener('input', function() {
 // Do something 
});

1 Comment

This is working fine!
-2

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.

jsfiddle URL : https://jsfiddle.net/Miteshvghela/d31ey2oL/17/

const form = document.getElementsByTagName('form');

const n = form[0].elements.length

for(i=0; i<n; i++){
let textEle = form[0].elements[i];

    textEle.addEventListener('keyup', function(event){
        console.log(event.currentTarget.value)
    })
}

Comments

-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') 
})

5 Comments

This won't get input from pasting.
@Quentin, Can you please your code? I put the code to a link for your convenience. Make sure to check console for the logs.
I provided my code 7 years ago. It's the accepted answer of this question!
Only if you type into the field, not if you paste into the field.
That's exactly what I provided answer for.
-3

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

Comments

-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...")
    })
});

1 Comment

op requested "pure javascript" way, meaning no jQuery — hence the downvotes

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.