jviotti jviotti - 5 months ago 29
jQuery Question

jquery intercepting paste event

I've binded a paste event from an input:

$(document).ready(function(){
$('.myInput').bind("paste",function(e) {
console.log(e);
});
});​


Everytime I hit CTRL-V it returns the
e
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
e.srcElement.value
after getting the input value
before
the paste, then compare both string and eliminate the first part, returning by consecuence the value of the clipboard.

Answer

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

HTML:

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

jQuery:

$(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/

Comments