Best way to track onchange as-you-type in input type=“text”?

后端 未结 16 1451
天命终不由人
天命终不由人 2020-11-22 08:42

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

Is there a way to

16条回答
  •  忘掉有多难
    2020-11-22 08:58

    Javascript is unpredictable and funny here.

    • onchange occurs only when you blur the textbox
    • onkeyup & onkeypress doesn't always occur on text change
    • onkeydown occurs on text change (but cannot track cut & paste with mouse click)
    • onpaste & oncut occurs with keypress and even with the mouse right click.

    So, to track the change in textbox, we need onkeydown, oncut and onpaste. In the callback of these event, if you check the value of the textbox then you don't get the updated value as the value is changed after the callback. So a solution for this is to set a timeout function with a timeout of 50 mili-seconds (or may be less) to track the change.

    This is a dirty hack but this is the only way, as I researched.

    Here is an example. http://jsfiddle.net/2BfGC/12/

提交回复
热议问题