I want to copy text to clipboard using jquery. But somewhere I am missing. I have the following codes:
<span class="copy-btn" data-type="attribute" data-attr-name="data-clipboard-text" data-model="couponCode" data-clipboard-text="<?php echo $result->coupon_code; ?>">COPY CODE</span>
</div>
And jquery is as follows:
$(document).ready(function(){
$('.copy-btn').on("click", function(){
value = $(this).data('clipboard-text'); //Upto this I am getting value
var $temp = $("<input>");
$("body").append($temp);
$temp.val($(value).text()).select();
document.execCommand("copy");
$temp.remove();
})
})
So please correct me, how can I copy code to clipboard. I am getting the value of the text, but after that I am unable to proceed.
All you need to do is add data-clipboard-target="#toCopyElement" on any button, initialize it new Clipboard('. btn'); and it will copy the content of DOM with id toCopyElement to clipboard.
To copy text with the new Clipboard API, you will use the asynchronous writeText() method. This method accepts only one parameter - the text to copy to your clipboard. This can be a string, a template literal holding variables and other strings, or a variable used to hold a string.
Open the file that you want to copy items from. Select the first item that you want to copy, and press CTRL+C. Continue copying items from the same or other files until you have collected all of the items that you want. The Office Clipboard can hold up to 24 items.
For people looking for a simple function to copy text to clipboard
function copyToClipboard(text) {
var $temp = $("<input>");
$("body").append($temp);
$temp.val(text).select();
document.execCommand("copy");
$temp.remove();
}
This can be called with jQuery like this:
$('#copyButtonId').click(function () { copyToClipboard("this text was copied"); });
var copyToClipboard = function (text) {
var $txt = $('<textarea />');
$txt.val(text).css({ width: "1px", height: "1px" }).appendTo('body');
$txt.select();
if (document.execCommand('copy')) {
$txt.remove();
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With