jquery how to get the pasted content

Because the paste event is triggered before the inputs value is updated, the solution is to either:

  1. Capture the data from the clipboard instead, as the clipboards data will surely be the same as the data being pasted into the input at that exact moment.

  2. Wait until the value has updated using a timer

Luckily, years after the original answer was posted, most modern browsers now support the fantastic Clipboard API, a much more elegant solution to capturing data from the clipboard.

For browsers that don't support the Clipboard API, we could fall back to the unreliable event.clipboardData if we do some checking as to which version, if any, is supported in the browser.

As a final fallback, using a timer to delay until the inputs value is updated, will work in all browsers, making this a truly cross-browser solution.

I've made a convenient function that handles everything

function catchPaste(evt, elem, callback) {
  if (navigator.clipboard && navigator.clipboard.readText) {
    // modern approach with Clipboard API
    navigator.clipboard.readText().then(callback);
  } else if (evt.originalEvent && evt.originalEvent.clipboardData) {
    // OriginalEvent is a property from jQuery, normalizing the event object
    callback(evt.originalEvent.clipboardData.getData('text'));
  } else if (evt.clipboardData) {
    // used in some browsers for clipboardData
    callback(evt.clipboardData.getData('text/plain'));
  } else if (window.clipboardData) {
    // Older clipboardData version for Internet Explorer only
    callback(window.clipboardData.getData('Text'));
  } else {
    // Last resort fallback, using a timer
    setTimeout(function() {
      callback(elem.value)
    }, 100);
  }
}

// to be used as 

$('#myid').on('paste', function(evt) {
  catchPaste(evt, this, function(clipData) {
    console.log(clipData);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="myid" />

Note that getting the data from the clipboard only gets you the pasted text, while waiting for the inputs value to update is the only solution above that actually gets the entire value of the input, including the newly pasted text.


The accepted answer is actually hacky and ugly, seems to be suggested quite often for the paste event on stackoverflow. I think a better way to do it is this

$('#someInput').bind('paste', function(e) {
    var data = e.originalEvent.clipboardData.getData('Text');
    //IE9 Equivalent ==> window.clipboardData.getData("Text");   
});

Tags:

Jquery

Paste