I have this right now:
<input type="text" placeholder="Paste text" onPaste="alert(this.value);">
This does infact work, except, it returns a blank alert window. I don't get any value. Help?
The onpaste event occurs when the user pastes some content in an element. Note: Although the onpaste event is supported by all HTML elements, it is not actually possible to paste some content in, for example, a <p> element, UNLESS the element has set contenteditable to "true" (See "More Examples" below).
Use navigator. clipboard to get access to the clipboard. Use writeText() to copy text into the clipboard. Use readText() to paste the text.
The onpaste
event fires before the input
's value
is changed. You need something such as a setTimeout
:
<input type="text" placeholder="Paste text" onPaste="var e=this; setTimeout(function(){alert(e.value);}, 4);">
I'm storing a reference to this
inside a global var as this
is not accessible inside the scope of a timeout function which is attached to the window object.
I'm using 4 miliseconds as the Timeout as it's the minimum valid Interval/Timeout in the HTML5 specification. Edit: As noted in the comments, you may also use 0
miliseconds as timeOut which is automatically recalculated to 4
. jsPerf tests.
Fiddle
You may as well use a function call inside your onpaste
event passing this
as a parameter to prevent your HTML mixing with JS too much. :)
And here's a function easier to read and which you can use in multiple inputs:
function pasted(element) { setTimeout(function(){ alert(element.value); }, 0); //or 4 }
Which can be called with simply onPaste="pasted(this)"
for any input.
Fiddle
This is because the onpaste
event fires before the content gets pasted into the element (link) so it's not there yet at the time you handle it.
Modern browsers support methods of obtaining clipboard data inside the event handler. Refer to JavaScript get clipboard data on paste event (Cross browser) for cross-browser solution attempts.
Also, you can always work around your issue by simply starting a timer in the event handler function (10ms should be enough) that would check your input value later.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With