Cross-browser JavaScript input live change/paste d

2019-03-19 04:03发布

Is there a cross-browser way to detect live changes to an input field?

By live, I mean not when the field loses focus, and not on the next keypress, and so on. Immediately or something like it.

Using combinations of jQuery and .change(), .keyup(), .bind('paste') and so on I can get working live change detection in some browsers, but not all. Using different combinations will make it work somewhat in other browsers.

The trickiest thing to get working is mouse manipulation of the input field - selecting text and moving it (which is essentially cut and paste), right-clicking and pasting or cutting, etc. For some reason even .mousedown() and .mouseup() don't seem to cut it.

The only cross-browser solution I can think of right now is to check the input field value every 100-or-so milliseconds and compare the value against a stored value. But this seems like overkill when the event-based solution comes so close.

Is there a jQuery plug-in that does this already? Or is there some other way to achieve this?

2条回答
爷的心禁止访问
2楼-- · 2019-03-19 04:29

To complete your change and key handlers, you can add handlers for cut/copy/paste. They work in Firefox >=3, IE, Safari and Chrome (but not in Opera/Konqueror).

Would that cover everything for your use case?

查看更多
Juvenile、少年°
3楼-- · 2019-03-19 04:30

Depending on the Browsers you need to support you might use HTML5's oninput.
It fires immediately when the monitored input changes. In jQuery you would just do:

$('#my-input').bind('input', function(e) {
    console.log("#my-input's value changed");
});
查看更多
登录 后发表回答