8

I'm trying to trigger a paste event in a textarea with jQuery, but this subject is quite new to me.

I've seen how one can manually trigger a keydown event simulating pressing a specific key like this:

var e = $.Event("keydown")
e.which = 50
$('#textarea1').trigger(e)

But how can I manually trigger a paste event with a provided string of text that effectively simulates a Ctrl+V or right-click > paste of a string like "Foobar"?

I have tried to simply set the value of textarea but this does not trigger a paste event.

EDIT:

I have also tried this (to simulate Ctrl+V) but no luck (ref):

e = $.Event("keydown");        
e.which = 86; // 'V' key
e.ctrlKey = true;
$("input").trigger(e);
Community
  • 1
  • 1
Submits
  • 229
  • 1
  • 2
  • 10

2 Answers2

3

I realise this is an old question, but you were on the right track.

To manually trigger a Paste event using jQuery, you need to use the paste event type, e.g.:

const e = $.Event('paste');
$('#textarea').val('some text').trigger(e);

or:

$('#textarea').val('some text').trigger('paste');
dilico
  • 694
  • 1
  • 6
  • 14
-6

Here is a solution you can try:

$('body').on('paste',function(e) {
    e.preventDefault();
    var text = (e.originalEvent || e).clipboardData.getData('text/plain');
    alert(text);
});
Vladimir
  • 176
  • 1
  • 1
  • 12