-2

I have an html file with a table collecting in every row several web links (url), and in the same table I would like to have a button for every row, that copies to the Clipboard the link of that row (embedded as 'href' in an anchor tag), giving to the user a feedback popup.

I've tried in several ways but it seems that most of the available examples show how to achieve that just for input fields, moreover with hard-coded functions that do not receive as a parameter the reference id for the text to be copied.

Any ideas?

-UPDATE- I solved my problem thanks to the suggestion of Maassander. Unfortunately the suggested thread was not specific enough for my issue: How do I copy to the clipboard in JavaScript?

Thorh73
  • 407
  • 1
  • 4
  • 14
  • 1
    Does this answer your question? [How do I copy to the clipboard in JavaScript?](https://stackoverflow.com/questions/400212/how-do-i-copy-to-the-clipboard-in-javascript) – Nicolas Nov 13 '19 at 14:29
  • Thanks a lot, but that thread didn't exactly served my purpose. I needed specifically to copy href contents from many rows of one html table, using buttons, and Maassander's answers definitely solved my problem. Thanks again. – Thorh73 Nov 26 '19 at 12:35

1 Answers1

1

The most basic version of this would look something like this I guess:

var rows = document.getElementsByClassName('table-row');

for (var i = 0; i < rows.length; i++){
  var button = rows[i].querySelector('button');
  
  button.addEventListener('click', function(e){
    var link = e.target.closest('tr').querySelector('a');
    var tempText = document.createElement('textarea');
    tempText.value = link.href;
    document.body.appendChild(tempText);
    tempText.select();
    document.execCommand('copy');
    document.body.removeChild(tempText);
  });
}
<table>
  <tr class="table-row">
    <td><a href="https://www.google.com">Google</a></td>
    <td><button type="button">Copy</button></td>
  </tr>
  <tr class="table-row">
    <td><a href="https://stackoverflow.com/">Stack Overflow</a></td>
    <td><button type="button">Copy</button></td>
  </tr>
</table>
maassander
  • 58
  • 5
  • Thanks a lot Maassander, it seems exactly what I was looking for and in your snippet it works like a charm. Sorry for my ignorance on the topic, but I would I embed the necessary javascript code in my html file? I've tried using the – Thorh73 Nov 19 '19 at 15:23
  • @Thorh73, the first part of my answer is what you would put within tags. Can you edit your question and place your current code there? That would make it easier to spot where you are going wrong. – maassander Nov 19 '19 at 17:51
  • Thanks a lot... my mistake was putting the script part BEFORE the html code for the table: it that situation the script code is not able to identify the buttons. When I moved the script part AFTER the code for the table, everything worked as expected! Thanks a lot! – Thorh73 Nov 20 '19 at 16:11