jviotti jviotti - 4 months ago 21x
jQuery Question

jquery intercepting paste event

I've binded a paste event from an input:

$('.myInput').bind("paste",function(e) {

Everytime I hit CTRL-V it returns the
event object.

I want to get the data the user is about to paste in the input.

By inspecting the event object I found the value in several places such as:

  • e.srcElement.value

  • e.target.value

But those ones return the value in the input after the paste happened. So If I paste some text after I entered another string, I'll get both strings concatenated.

I've search trought the internet and found nothing but ugly flash solutions.

Is there a clean way to do this in jquery?

I thought about getting the whole text with
after getting the input value
the paste, then compare both string and eliminate the first part, returning by consecuence the value of the clipboard.


Maybe this is what your trying to do, not 100% sure:


<input type="text" id="test" class="myInput" value="This is some default text" />​


$(document).ready(function () {
    $('input').on('paste', function (e) { //Attach paste event handler for all inputs
        $(this).val('').val(e.target.value); //Clear the current value, then insert the value of the data that was pasted

Fiddle: http://jsfiddle.net/PMq6U/