Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery intercepting paste event

Tags:

jquery

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.

like image 854
jviotti Avatar asked Dec 20 '12 02:12

jviotti


2 Answers

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/

like image 193
PhearOfRayne Avatar answered Dec 12 '22 06:12

PhearOfRayne


clipboardData works for modern browsers (IE11+, Firefox, Chrome...).

$(document).ready(function(){
      $('.myInput').on('paste', function (e) {
          var dt = e.originalEvent.clipboardData;
          if(dt && dt.items && dt.items[0]){
              dt.items[0].getAsString(function(text){
                  console.log(text); //the pasted content
              });
          }else if(dt && 'getData' in dt){
              console.log(dt.getData('text')); //the pasted content
          }
      });
});

http://jsfiddle.net/6n10y0ds/9/

https://developer.mozilla.org/en-US/docs/Web/API/DataTransfer

like image 32
cuixiping Avatar answered Dec 12 '22 05:12

cuixiping