How to copy multiple text input to clipboard

Tags: , , , ,



I have already learned how to copy a single text input to the clipboard. However I can’t seem to figure out how to copy multiple text inputs to the clipboard. Can someone please help me figure this out for my project. Cheers!

function myFunction() {
  var copyText = document.getElementById("entry.1208432141");
  copyText.select();
  copyText.setSelectionRange(0, 99999) document.execCommand("copy");

Answer

As CBroe already wrote, you overwrite your buffer with every further copying process and thus only the last entry remains. One possibility would be to create a new field for a short time and to store the content of all elements there and then to copy it to the buffer. It could look something like this:

function myFunction(idList) {
   let text = "";
   idList.forEach(fieldid => {
     text += document.getElementById(fieldid).value;
   });

   const tempTextarea = document.createElement("textarea");
   tempTextarea = text;
   document.body.appendChild(tempTextarea);
   tempTextarea.select();
   tempTextarea.setSelectionRange(0, 99999) document.execCommand("copy");
   document.body.removeChild(tempTextarea);
}

myfunction(['entry.1208432141','entry.1208432888'])

Of course, this is not a complete code. For example, there is no error handling if a field was not found. But it shows how it could work.

Update

Another method would be to use the current browser api. This is only possible with modern browsers. But be careful, this method is asynchronous. Can I use navigator.clipboard?

if (navigator.clipboard) {
  navigator.clipboard.writeText(text).then(function() {
    console.log('Async: Copying to clipboard was successful!')
  }, function(clipboardError) {
    console.error('Async: Could not copy text: ', clipboardError)
  })
}


Source: stackoverflow