Best way to track onchange as-you-type in input ty

2018-12-31 14:42发布

In my experience, input type="text" onchange event usually occurs only after you leave (blur) the control.

Is there a way to force browser to trigger onchange every time textfield content changes? If not, what is the most elegant way to track this “manually”?

Using onkey* events is not reliable, since you can right-click the field and choose Paste, and this will change the field without any keyboard input.

Is setTimeout the only way?.. Ugly :-)

14条回答
听够珍惜
2楼-- · 2018-12-31 15:26

Below code works fine for me with Jquery 1.8.3

HTML : <input type="text" id="myId" />

Javascript/JQuery:

$("#myId").on('change keydown paste input', function(){
      doSomething();
});
查看更多
浮光初槿花落
3楼-- · 2018-12-31 15:26

onkeyup happens after you type for example I press t when I lift the finger the action happens but on keydown the action happens before I digit the character t

Hope this is helpful for someone.

So onkeyup is better for when you want to send what you just typed now.

查看更多
登录 后发表回答