12

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.

Erik Philips
  • 53,428
  • 11
  • 128
  • 150
Amit
  • 239
  • 1
  • 2
  • 8

3 Answers3

14

You have an error on this line:

$temp.val($(value).text()).select();

Since value is already a string, you don't need to try to get it as an input field. Simply use this:

$temp.val(value).select();

Here's a working example.

VVV
  • 7,563
  • 3
  • 34
  • 55
2
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();
            }
        };
Alper Ebicoglu
  • 8,884
  • 1
  • 49
  • 55
2

html:

<button address="any text" class="btn btn-login copyToClipboard"><span> copy</span>

js file:

$('.copyToClipboard').click(function () {
        let str = $(this).attr('address');
        const el = document.createElement('textarea');
        el.value = str;
        el.setAttribute('readonly', '');
        el.style.position = 'absolute';
        el.style.left = '-9999px';
        document.body.appendChild(el);
        el.select();
        document.execCommand('copy');
        document.body.removeChild(el);
    })