Roy Berris
Roy Berris

Reputation: 1592

JavaScript - run function on <input> change - NO JQUERY

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">

Upvotes: 13

Views: 23495

Answers (2)

Tushar
Tushar

Reputation: 87203

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

Upvotes: 4

CodingIntrigue
CodingIntrigue

Reputation: 78545

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">

Upvotes: 20

Related Questions