4

How do I copy a variable into the clipboard?

It always return:

Uncaught TypeError: copyText.select is not a function

Code

function copy() {
    var allDesCode2 = document.getElementsByClassName("desCode2");
    var copyText = "ABC";
    for(var i=0; i<allDesCode2.length; i++) {
        copyText += allDesCode2[i].innerHTML;
    }
    copyText.select();
    document.execCommand("copy");
}
Community
  • 1
  • 1
  • `.select()` is a `HTMLInputElement` method but you are using it on `String`. See [this question](https://stackoverflow.com/questions/400212/how-do-i-copy-to-the-clipboard-in-javascript?rq=1) to copy to clipboard. – yqlim Mar 15 '19 at 07:26
  • 3
    Possible duplicate of [How do I copy to the clipboard in JavaScript?](https://stackoverflow.com/questions/400212/how-do-i-copy-to-the-clipboard-in-javascript) – yqlim Mar 15 '19 at 07:27

3 Answers3

2

The copy() function below can help to copy a string from a variable. You can use this method in pure JavaScript without the help of any libraries, such as jQuery.

function copy() {

    var copyText = "Hooray ! I will be copied";
    var el = document.createElement('textarea');
    el.value = copyText;
    el.setAttribute('readonly', '');
    el.style = {
        position: 'absolute',
        left: '-9999px'
    };
    document.body.appendChild(el);
    el.select();
    document.execCommand('copy');
    document.body.removeChild(el);
}
<button onclick="copy()">Copy</button>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Googlian
  • 6,077
  • 3
  • 38
  • 44
0

I assume you were using this article as a reference. But in this example .select() was used on <input> element, and you're trying to execute this method on a variable.

You can look at this question (your question is a possible duplicate of this). It has a plenty of useful answers which will help you.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
flppv
  • 4,111
  • 5
  • 35
  • 54
0

You just try to select text without any input. That's mistake one. Also I just read the copy event must be inside the click event (maybe there are more events to copy - reference).

I attached the copy function on your div, put its HTML content into the input, and then copy it.

function copy() {
  var allDesCode2 = document.getElementsByClassName("desCode2");
  var copyText = "ABC";
  for (var i = 0; i < allDesCode2.length; i++) {
    copyText += allDesCode2[i].innerHTML;
  }
  $('input').val(copyText).select();
  document.execCommand('copy');
}
$('.desCode2').on('click', copy);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="desCode2">123123123123</div>
<input>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131