简体   繁体   中英

How to copy a variable into the clipboard

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");
}

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> 

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> 

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM