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

丶灬走出姿态 提交于 2020-12-05 04:56:29

问题


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

回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/30806948/javascript-run-function-on-input-change-no-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!