13

I want to run a function when a HTML <input/> tag changes. How do I do this? There are some answers for this but they are all in jQuery and I want plain javascript. Can someone give me a simple example? Thanks!

I want the input to be a type as text:

<input type="text" id="change">
0

2 Answers 2

20

You can use the input event. This will trigger not only on key up and paste, but also other text modification events such as drag & drop.

change.addEventListener("input", function (e) {
    alert(this.value);
});
<input type="text" id="change">

Sign up to request clarification or add additional context in comments.

Comments

4

Use addEventListener:

document.getElementById('change').addEventListener("keyup", function (evt) {
    console.log(this.value);
}, false);

Demo: http://jsfiddle.net/tusharj/y9xcoqja/

Docs: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener

The EventTarget.addEventListener() method registers the specified listener on the EventTarget it's called on. The event target may be an Element in a document, the Document itself, a Window, or any other object that supports events (such as XMLHttpRequest).

EDIT

To bind multiple events on the same element:

var element = document.getElementById('change');

function myEventHandler(event) {

}


element.addEventListener("keyup", function (evt) {
    myEventHandler(evt);
}, false);

element.addEventListener("change", function (evt) {
    myEventHandler(evt);
}, false);

4 Comments

I'd also add mouseup event, or cut&paste events wouldn't be intercepted
@AndreaLigios how do I add a second event?
Thanks Tushar but the Answer from RGraham makes your 2 eventListeners, 1 eventListener using the input event
@Finiox I've just added those two event listeners to show how multiple events can be added on a single element. You should use the keyup event as shown above

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.