Copy output of a JavaScript variable to the clipboard

harman picture harman · Nov 22, 2015 · Viewed 106.1k times · Source

I have no knowledge of JavaScript, but I managed to put this code together using bits and bolts from various Stack Overflow answers. It works OK, and it outputs an array of all selected checkboxes in a document via an alert box.

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);
  }
  return checkbx;
}

And to call it I use:

<button id="btn_test" type="button" >Check</button>
<script>
    document.getElementById('btn_test').onclick = function() {
        var checkedBoxes = getSelectedCheckboxes("my_id");
        alert(checkedBoxes);
    }
</script>

Now I would like to modify it so when I click the btn_test button the output array checkbx is copied to the clipboard. I tried adding:

checkbx = document.execCommand("copy");

or

checkbx.execCommand("copy");

at the end of the function and then calling it like:

<button id="btn_test" type="button" onclick="getSelectedCheckboxes('my_id')">Check</button>

But it does not work. No data is copied to clipboard.

Answer

walkman picture walkman · Sep 8, 2017
function copyToClipboard(text) {
    var dummy = document.createElement("textarea");
    // to avoid breaking orgain page when copying more words
    // cant copy when adding below this code
    // dummy.style.display = 'none'
    document.body.appendChild(dummy);
    //Be careful if you use texarea. setAttribute('value', value), which works with "input" does not work with "textarea". – Eduard
    dummy.value = text;
    dummy.select();
    document.execCommand("copy");
    document.body.removeChild(dummy);
}
copyToClipboard('hello world')
copyToClipboard('hello\nworld')