Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy to clipboard using jquery?

Tags:

jquery

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.

like image 657
Amit Avatar asked Nov 09 '17 16:11

Amit


People also ask

How do I Copy to the clipboard in jquery?

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.

How do I Copy to the clipboard in Javascript?

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.

How do I transfer data to clipboard?

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.


2 Answers

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"); });
like image 69
N T Avatar answered Nov 15 '22 20:11

N T


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();
            }
        };
like image 35
Alper Ebicoglu Avatar answered Nov 15 '22 22:11

Alper Ebicoglu