On my site users can paste text (in this case a url) into an input field. I\'d like to capture the value of the text that was pasted using jQuery. I\'ve got this to work in
Listen for the change
event as well as paste
. change
will reliably fire on a changed field before submission, whereas paste
only happens on browsers that support it on an explicit paste; it won't be triggered by other editing actions such as drag-and-drop, cut-copy, undo-redo, spellcheck, IME substitution etc.
The problem with change
is that it doesn't fire straight away, only when editing in a field is finished. If you want to catch all changes as they happen, the event would be input
... except that this is a new HTML5 feature that isn't supported everywhere (notably: IE<9). You could nearly do it by catching all these events:
$('.url').bind('input change paste keyup mouseup',function(e){
...
});
But if you want to definitely catch every change quickly on browsers that don't support input
, you have no choice but to poll the value on a setInterval
.
jQuery has a problem with the live-method with the paste-event in the IE; workaround:
$(document).ready(function() {
$(".url").bind('paste', function(event) {
var _this = this;
// Short pause to wait for paste to complete
setTimeout( function() {
var text = $(_this).val();
$(".display").html(text);
}, 100);
});
});
Fiddle: http://jsfiddle.net/Trg9F/
$('input').on('paste', function(e) {
// common browser -> e.originalEvent.clipboardData
// uncommon browser -> window.clipboardData
var clipboardData = e.clipboardData || e.originalEvent.clipboardData || window.clipboardData;
var pastedData = clipboardData.getData('text');
});
Even better is it to use e.originalEvent.clipboardData.getData('text'); to retrieve pasted data;
$("input").on("paste", function(e) {
var pastedData = e.originalEvent.clipboardData.getData('text');
// ... now do with pastedData whatever you like ...
});
This way you can avoid timeouts and it is supported on all major browsers.
Maybe try using the onblur
event instead. So the user c/p into the input and when they leave the field the script checks what's there. This could save a whole lot of hassle, since it works for mouse and key c/p as well as manually entered input.