Copy Output of a JavaScript Variable to the Clipboard

Copy output of a JavaScript variable to the clipboard

OK, I found some time and followed the suggestion by Teemu and I was able to get exactly what I wanted.

So here is the final code for anyone that might be interested. For clarification, this code gets all checked checkboxes of a certain ID, outputs them in an array, named here checkbx, and then copies their unique name to the clipboard.

JavaScript function:

function getSelectedCheckboxes(chkboxName) {
var checkbx = [];
var chkboxes = document.getElementsByName(chkboxName);
var nr_chkboxes = chkboxes.length;
for(var i=0; i<nr_chkboxes; i++) {
if(chkboxes[i].type == 'checkbox' && chkboxes[i].checked == true) checkbx.push(chkboxes[i].value);
}
checkbx.toString();

// Create a dummy input to copy the string array inside it
var dummy = document.createElement("input");

// Add it to the document
document.body.appendChild(dummy);

// Set its ID
dummy.setAttribute("id", "dummy_id");

// Output the array into it
document.getElementById("dummy_id").value=checkbx;

// Select it
dummy.select();

// Copy its contents
document.execCommand("copy");

// Remove it as its not needed anymore
document.body.removeChild(dummy);
}

And its HTML call:

<button id="btn_test" type="button" onclick="getSelectedCheckboxes('ID_of_chkbxs_selected')">Copy</button>

How to copy a variable into the clipboard

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>

How to copy the value of variable in javascript

var getNum1 = function() {  return 1;};
var getNum2 = function() { return 2;};
var num1 = getNum1();var num2 = getNum2();var result = ((num1 * num2) / 3) - 1;
var executeCopy = function() { var copyhelper = document.createElement("input"); copyhelper.className = 'copyhelper' document.body.appendChild(copyhelper); copyhelper.value = result; copyhelper.select(); document.execCommand("copy"); document.body.removeChild(copyhelper);};
document.getElementById('mybutton').addEventListener('click', function() { executeCopy();
alert("your results has been copied");});
.copyhelper {  position: absolute;}
<button id='mybutton'>Copy to clipboard</button>

How to copy a text from output to clipboard?

Try this solution, or hack, hack because of Output element do not have a select function, So what we did we copied the output value from output element to a hidden input element and then assign the value from hidden input element to the clipboard

So this will help!

<!DOCTYPE html><html><body><button onclick="myFunction()">Copy output text</button>
<form oninput="x.value=parseInt(a.value)+parseInt(b.value)">0<input type="range" id="a" value="50">100+<input type="number" id="b" value="50">=<output id="myInput" name="x" for="a b"></output><input type="hidden" id="dummyMyInput" /></form>
<script>function myFunction() { debugger; var copyText = document.getElementById("myInput").value; document.getElementById("dummyMyInput").value = copyText; copyText = document.getElementById("dummyMyInput"); copyText.select(); document.execCommand("copy"); alert("Copied the text: " + copyText.value);}</script>
</body></html>

Copy output of a JavaScript variable to the clipboard (multi-line)

As said in the comments, an input doesn't have line breaks, so just replace input with textarea in your code

How do I copy to the clipboard in JavaScript?

Overview

There are three primary browser APIs for copying to the clipboard:

  1. Async Clipboard API [navigator.clipboard.writeText]

    • Text-focused portion available in Chrome 66 (March 2018)
    • Access is asynchronous and uses JavaScript Promises, can be written so security user prompts (if displayed) don't interrupt the JavaScript in the page.
    • Text can be copied to the clipboard directly from a variable.
    • Only supported on pages served over HTTPS.
    • In Chrome 66 pages inactive tabs can write to the clipboard without a permissions prompt.
  2. document.execCommand('copy') (deprecated) /p>

    • Most browsers support this as of ~April 2015 (see Browser Support below).
    • Access is synchronous, i.e. stops JavaScript in the page until complete including displaying and user interacting with any security prompts.
    • Text is read from the DOM and placed on the clipboard.
    • During testing ~April 2015 only Internet Explorer was noted as displaying permissions prompts whilst writing to the clipboard.
  3. Overriding the copy event

    • See Clipboard API documentation on Overriding the copy event.
    • Allows you to modify what appears on the clipboard from any copy event, can include other formats of data other than plain text.
    • Not covered here as it doesn't directly answer the question.

General development notes

Don't expect clipboard related commands to work whilst you are testing code in the console. Generally, the page is required to be active (Async Clipboard API) or requires user interaction (e.g. a user click) to allow (document.execCommand('copy')) to access the clipboard see below for more detail.

IMPORTANT (noted here 2020/02/20)

Note that since this post was originally written deprecation of permissions in cross-origin IFRAMEs and other IFRAME "sandboxing" prevents the embedded demos "Run code snippet" buttons and "codepen.io example" from working in some browsers (including Chrome and Microsoft Edge).

To develop create your own web page, serve that page over an HTTPS connection to test and develop against.

Here is a test/demo page which demonstrates the code working:
https://deanmarktaylor.github.io/clipboard-test/

Async + Fallback

Due to the level of browser support for the new Async Clipboard API, you will likely want to fall back to the document.execCommand('copy') method to get good browser coverage.

Here is a simple example (may not work embedded in this site, read "important" note above):

function fallbackCopyTextToClipboard(text) {
var textArea = document.createElement("textarea");
textArea.value = text;

// Avoid scrolling to bottom
textArea.style.top = "0";
textArea.style.left = "0";
textArea.style.position = "fixed";

document.body.appendChild(textArea);
textArea.focus();
textArea.select();

try {
var successful = document.execCommand('copy');
var msg = successful ? 'successful' : 'unsuccessful';
console.log('Fallback: Copying text command was ' + msg);
} catch (err) {
console.error('Fallback: Oops, unable to copy', err);
}

document.body.removeChild(textArea);
}
function copyTextToClipboard(text) {
if (!navigator.clipboard) {
fallbackCopyTextToClipboard(text);
return;
}
navigator.clipboard.writeText(text).then(function() {
console.log('Async: Copying to clipboard was successful!');
}, function(err) {
console.error('Async: Could not copy text: ', err);
});
}

var copyBobBtn = document.querySelector('.js-copy-bob-btn'),
copyJaneBtn = document.querySelector('.js-copy-jane-btn');

copyBobBtn.addEventListener('click', function(event) {
copyTextToClipboard('Bob');
});

copyJaneBtn.addEventListener('click', function(event) {
copyTextToClipboard('Jane');
});
<div style="display:inline-block; vertical-align:top;">
<button class="js-copy-bob-btn">Set clipboard to BOB</button><br /><br />
<button class="js-copy-jane-btn">Set clipboard to JANE</button>
</div>
<div style="display:inline-block;">
<textarea class="js-test-textarea" cols="35" rows="4">Try pasting into here to see what you have on your clipboard:

</textarea>
</div>

Copying PHP variables to the clipboard with javascript

The whole purpose of IDs is to uniquely IDentify an element. Also, that's not how execCommand() works (how can your code possibly know that text you want copied?).

Getting rid of IDs (which you don't really need at all) you could do something like:

function copyTo(input) {
input.select();
document.execCommand("copy");
}
<input type="text" value="First" onclick="copyTo(this)">
<input type="text" value="Second" onclick="copyTo(this)">
<input type="text" value="Third" onclick="copyTo(this)">


Related Topics



Leave a reply



Submit