根据我的经验,input type="text" onchange事件通常只发生在你离开(模糊)控件之后。
有办法迫使浏览器触发onchange每次文本字段内容的变化?如果不是,那么“手动”跟踪这种情况的最佳方法是什么?
使用onkey* events是不可靠的,因为您可以右键单击字段并选择粘贴,这将在没有任何键盘输入的情况下更改字段。
setTimeout是唯一的方法吗?丑:-)
根据我的经验,input type="text" onchange事件通常只发生在你离开(模糊)控件之后。
有办法迫使浏览器触发onchange每次文本字段内容的变化?如果不是,那么“手动”跟踪这种情况的最佳方法是什么?
使用onkey* events是不可靠的,因为您可以右键单击字段并选择粘贴,这将在没有任何键盘输入的情况下更改字段。
setTimeout是唯一的方法吗?丑:-)
当前回答
方法一:为输入添加事件监听器:
element.addEventListener("input", myFunction);
方法2:用JavaScript定义oninput属性:
element.oninput = function()
{
myFunction();
};
方法3:用HTML定义oninput属性:
<input type="text" oninput="myFunction();">
其他回答
您也可以使用按下键、按上键和按下键事件。
“输入”对我很有用。
var searchBar = document.getElementById("searchBar");
searchBar.addEventListener("input", PredictSearch, false);
下面的代码为我工作良好的Jquery 1.8.3
HTML: <输入类型=“文本”id=“myId”/>
Javascript/JQuery:
$("#myId").on('change keydown paste input', function(){
doSomething();
});
更新:
参见Another answer(2015)。
2009年原文答案:
你想让onchange事件触发按下键,模糊和粘贴?这是魔法。
如果你想在他们输入时跟踪更改,使用"onkeydown"。如果你需要用鼠标捕捉粘贴操作,请使用“onpaste”(IE, FF3)和“oninput”(FF, Opera, Chrome, Safari1)。
在Safari上<textarea>破碎。使用textInput代替
使用oninput而不是onchange。
index . html
<html>
<head>
<title>title here</title>
<script src="index.js"></script>
</head>
<body>
<input oninput="onclickhandler(this)"></input>
</body>
</html>
script.js
function onclickhandler(e) {
console.log(e.value);
}