I have a little trouble catching a pasted text into my input:
<input type="text" id="myid" val="default">
$('#myid').on('paste',function(){
console.log($('#myid').val());
});
console.log shows:
default
How I catch the pasted text and get ready to use?
Because the
pasteevent is triggered before the inputs value is updated, the solution is to either:Capture the data from the clipboard instead, as the clipboards data will surely be the same as the data being pasted into the input at that exact moment.
Wait until the value has updated using a timer
Luckily, years after the original answer was posted, most modern browsers now support the fantastic Clipboard API, a much more elegant solution to capturing data from the clipboard.
For browsers that don’t support the Clipboard API, we could fall back to the unreliable
event.clipboardDataif we do some checking as to which version, if any, is supported in the browser.As a final fallback, using a timer to delay until the inputs value is updated, will work in all browsers, making this a truly cross-browser solution.
I’ve made a convenient function that handles everything
Note that getting the data from the clipboard only gets you the pasted text, while waiting for the inputs value to update is the only solution above that actually gets the entire value of the input, including the newly pasted text.