Copy output of a JavaScript variable to the clipbo

2019-01-18 01:31发布

问题:

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.

回答1:

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>


回答2:

lbrutti's idea of an answer is good, but he writes wrong code!

function copyToClipboard(text){
    var dummy = document.createElement("input");
    document.body.appendChild(dummy);
    dummy.setAttribute('value', text);
    dummy.select();
    document.execCommand("copy");
    document.body.removeChild(dummy);
}
copyToClipboard('Hello, World!')


回答3:

Very useful. I modified it to copy a JavaScript variable value to clipboard:

function copyToClipboard(val){
    var dummy = document.createElement("input");
    document.body.appendChild(dummy);
    $(dummy).css('display','none');
    dummy.setAttribute("id", "dummy_id");
    document.getElementById("dummy_id").value=val;
    dummy.select();
    document.execCommand("copy");
    document.body.removeChild(dummy);
}


回答4:

For general purposes of copying any text to the clipboard, I wrote the following function:

function textToClipboard (text) {
    var dummy = document.createElement("textarea");
    document.body.appendChild(dummy);
    dummy.value = text;
    dummy.select();
    document.execCommand("copy");
    document.body.removeChild(dummy);
}

The value of the parameter is inserted into value of a newly created <textarea>, which is then selected, its value is copied to the clipboard and then it gets removed from the document.



回答5:

I just want to add, if someone wants to copy two different inputs to clipboard. I also used the technique of putting it to a variable then put the text of the variable from the two inputs into a text area.

Note: the code below is from a user asking how to copy multiple user inputs into clipboard. I just fixed it to work correctly. So expect some old style like the use of var instead of let or const. I also recommend to use addEventListener for the button.

    function doCopy() {

        try{
            var unique = document.querySelectorAll('.unique');
            var msg ="";

            unique.forEach(function (unique) {
                msg+=unique.value;
            });

            var temp =document.createElement("textarea");
            var tempMsg = document.createTextNode(msg);
            temp.appendChild(tempMsg);

            document.body.appendChild(temp);
            temp.select();
            document.execCommand("copy");
            document.body.removeChild(temp);
            console.log("Success!")


        }
        catch(err) {

            console.log("There was an error copying");
        }
    }
<input type="text" class="unique" size="9" value="SESA / D-ID:" readonly/>
<input type="text" class="unique" size="18" value="">
<button id="copybtn" onclick="doCopy()"> Copy to clipboard </button>



回答6:

When you need to copy a variable to the clipboard in the Chrome dev console, you can simply use the copy() command.

https://developers.google.com/web/tools/chrome-devtools/console/command-line-reference#copyobject