Click button to copy cell column comma separated

I have an HTML table with one specific column that I want to copy to the clipboard by pressing a button. The column contains container numbers, and I’ve given it a class “.container”

Here is the code I have so far. HTML:

<button onclick="copyToClipboard('.container')">Copy container #s</button>

Javascript:

<script>
    function copyToClipboard(element) {
        var $temp = $("<input>");
        $("body").append($temp);
        $temp.val($(element).text()).select();
        document.execCommand("copy");
        $temp.remove();
      }
</script>

Adapted from this question, the only change I made was making it a class selector instead of an ID selector to get a table range: Click button copy to clipboard using jQuery

When I click the button, it does copy the contents of all cells with class “.container”. The challenge is that it copies all cell contents without putting any spaces in between. Ideally, I would like to put a comma, line space, or some other kind of break between the different cell contents.

I’ve tried different varations of the code, like so:

$("body"+", ").append($temp);
    
$("body").append($temp+ ", ");
    
$("body").append($temp).append(", ");

But these do not work. I have a feeling that the reason it doesn’t work is that the $temp variable already contains the concatenated string of all the cell contents, so it’s too late to do any string splitting at this point.

therefore, I think the change needs to happen on this line:

<button onclick="copyToClipboard('.container')">Copy container #s</button>

But I’m just not sure how to modify it so that it loops over each cell, and appends a comma in between. Any help is appreciated

Answer

For separating with , you have to run a loop through the tds. You can map all the tds text and join it with ,.

$(element).find('td').map(function(){
     return $(this).text();
}).get();

See the Snippet below:

function copyToClipboard(element) {
  var $temp = $("<input>");
  $("body").append($temp);

  //Added below code;
  var cellValues = $(element).find('td').map(function(){
      return $(this).text();
  }).get();
  var allCellValues = cellValues.join(',');
  //Added above code;
  
  $temp.val(allCellValues).select();
  document.execCommand("copy");
  $temp.remove();
  
  console.log(allCellValues);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr class="container"><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td></tr>
</table>

<button onclick="copyToClipboard('.container')">Copy container #s</button>

You can test it here also.