Rick D
Rick D

Reputation: 55

Pressing button in row of table to copy cell to clipboard - Javascript

I was wondering if a guru could help me out with this one. I have a table with a button in each row. After pressing the copy button, it should copy the verbiage that is in cell 2 of that row. I am able to get an alert to come up, but I need it to copy to clip board, so a user can paste it to another application. Also, this method works in chrome, but not IE11. Is there a method that works for both? Thanks so much!

var a = document.getElementsByClassName('otherButton');

for (var i = 0; i < a.length; i++) {
  a[i].addEventListener('click', function() {

    var b = this.parentNode.parentNode.cells[1].textContent;
    alert(b);

  });
}
<table id="somerow">
  <tr>
    <th>CustomerNr</th>
    <th>Name</th>
    <th>Contact</th>
  </tr>
  <tr>
    <td>1</td>
    <td>Cigarettes Inc</td>
    <td>Rambo</td>
    <td><button class="otherButton">Copy</button></td>
  </tr>
  <tr>
    <td>22</td>
    <td>Razor</td>
    <td>David</td>
    <td><button class="otherButton">Copy</button></td>
  </tr>
  <tr>
    <td>3</td>
    <td>H&M</td>
    <td>Samuel Adams</td>
    <td><button class="otherButton">Copy</button></td>
  </tr>
</table>

Upvotes: 0

Views: 2167

Answers (1)

Mara Black
Mara Black

Reputation: 1751

Take a look at this copy-output-of-a-javascript-variable-to-the-clipboard but be aware that execCommand is deprecated. If your project allows external dependecies, you can use clipboardjs

var a = document.getElementsByClassName('otherButton');

for (var i = 0; i < a.length; i++) {
  a[i].addEventListener('click', function() {
    var b = this.parentNode.parentNode.cells[1].textContent;
    copyToClipboard(b);
    alert(b);
  });
}

function copyToClipboard(text) {
  var dummy = document.createElement("textarea");
  document.body.appendChild(dummy);
  dummy.value = text;
  dummy.select();
  document.execCommand("copy");
  document.body.removeChild(dummy);
}
<table id="somerow">
  <tr>
    <th>CustomerNr</th>
    <th>Name</th>
    <th>Contact</th>
  </tr>
  <tr>
    <td>1</td>
    <td>Cigarettes Inc</td>
    <td>Rambo</td>
    <td><button class="otherButton">Copy</button></td>
  </tr>
  <tr>
    <td>22</td>
    <td>Razor</td>
    <td>David</td>
    <td><button class="otherButton">Copy</button></td>
  </tr>
  <tr>
    <td>3</td>
    <td>H&M</td>
    <td>Samuel Adams</td>
    <td><button class="otherButton">Copy</button></td>
  </tr>
</table>

Upvotes: 2

Related Questions