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:06

You could use the keydown, keyup and keypress events as well.

查看更多
闭嘴吧你
3楼-- · 2018-12-31 15:07

Please, judge next approach using JQuery:

HTML:

<input type="text" id="inputId" />

Javascript(JQuery):

$("#inputId").keyup(function(){
        $("#inputId").blur();
        $("#inputId").focus();
});

$("#inputId").change(function(){
        //do whatever you need to do on actual change of the value of the input field
});
查看更多
墨雨无痕
4楼-- · 2018-12-31 15:11

2018 here, this is what I do:

$(inputs).on('change keydown paste input propertychange click keyup blur',handler);

If you can point out flaws in this approach, I would be grateful.

查看更多
ら面具成の殇う
5楼-- · 2018-12-31 15:12

"input" worked for me.

var searchBar  = document.getElementById("searchBar");
searchBar.addEventListener("input", PredictSearch, false);
查看更多
低头抚发
6楼-- · 2018-12-31 15:14

Update:

See Another answer (2015).


Original 2009 Answer:

So, you want the onchange event to fire on keydown, blur, and paste? That's magic.

If you want to track changes as they type, use "onkeydown". If you need to trap paste operations with the mouse, use "onpaste" (IE, FF3) and "oninput" (FF, Opera, Chrome, Safari1).

1Broken for <textarea> on Safari. Use textInput instead

查看更多
一个人的天荒地老
7楼-- · 2018-12-31 15:16

To track each try this example and before that completely reduce cursor blink rate to zero.

<body>
//try onkeydown,onkeyup,onkeypress
<input type="text" onkeypress="myFunction(this.value)">
<span> </span>
<script>
function myFunction(val) {
//alert(val);
var mySpan = document.getElementsByTagName("span")[0].innerHTML;
mySpan += val+"<br>";
document.getElementsByTagName("span")[0].innerHTML = mySpan;
}
</script>

</body>

onblur : event generates on exit

onchange : event generates on exit if any changes made in inputtext

onkeydown: event generates on any key press (for key holding long times also)

onkeyup : event generates on any key release

onkeypress: same as onkeydown (or onkeyup) but won't react for ctrl,backsace,alt other

查看更多
登录 后发表回答