I have an array that I would like to copy to the clipboard when I press the "c" key and do a left click on a button (see code below):
$(document).on('keydown', e => {
$(document).on('click', d => {
if (e.keyCode === 67) {
var dummyContent = [1, 2, 3];
var dummyContentTrue = dummyContent.join(', ');
var dummy = $('<input>').val(dummyContentTrue).appendTo('body').select()
document.execCommand('copy')
}
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
As the code shows, it creates a LOT of textboxes which I cannot have on my page, and after I let go of "c", the boxes do not delete. I have tried .remove()
on $('<input>')
, but still to no avail.
Any help is greatly appreciated! (FYI in my code snippet, make sure to hold the letter c key and left click at the same time to see a result).
ALSO an FYI I only want the copy to happen when both the c key and left click are pressed. If c key is not pressed, I do not want it to copy the data.
You need to call .remove()
on an element or list of elements
So, it should be either be $( "input" ).remove()
Or, you can assign the newly created input
to a variable and call remove
on that element
var dummy = $('<input>'); // newly created element
dummy.val(dummyContentTrue).appendTo('body').select()
document.execCommand('copy')
dummy.remove() // remove the element
Also, every time you keydown, a new click
handler is added to document
. So you need to move it out of there.