Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to manually trigger a paste event in a text area with specific text

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);
like image 267
Submits Avatar asked Sep 06 '16 08:09

Submits


1 Answers

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');
like image 88
dilico Avatar answered Oct 06 '22 00:10

dilico