javascriptinputcopy-paste

Javascript OnPaste return value


I have this code:

<input type="text" placeholder="Paste text" onPaste="alert(this.value);">

this.value is returned as empty, not as the pasted value. How can I get the pasted value?


Solution

  • 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