harman harman - 2 months ago 20
Javascript Question

Copy output of javascript variable to clipboard

I have no knowledge of JS but I managed to put this code together using bits and bolts from various stackoverflow 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.

Any help would be much appreciated.
Thanks

Answer

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.

JS 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>
Comments