-3

Given this HTML:

<html>
<body>
<table>
  <tr>
    <td>Copy This Text</td>
    <td><button type="button">Copy</button></td>
  </tr>
</table>
</body>
</html>

When the user clicks on that button, how can I copy the the text from first TD tag to clipboard?

Bharata
  • 11,779
  • 6
  • 27
  • 42
  • Welcome to Stack Overflow! Other users marked your question for low quality and need for improvement. I re-worded/formatted your input to make it easier to read/understand. Please review my changes to ensure they reflect your intentions. Feel free to drop me a comment in case you have further questions or feedback for me. – GhostCat Sep 04 '18 at 07:32

2 Answers2

0

The first way:

$(document).ready(function(){
   $("button").click(function(){
      $("td").append($("td").html());
   });
});

and you should remove the second <td> and put button outside

<button type="button">Copy</button>
Jon P
  • 17,053
  • 7
  • 44
  • 64
0

You can use the following code for jQuery:

function copyText(obj) 
{
    var tmpInput = $("<input>");
    $("body").append(tmpInput);
    var tdVal = $(obj).parent().prev().text();
    tmpInput.val(tdVal).select();
    document.execCommand("copy");
    tmpInput.remove();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td>Copy This Text</td>
    <td><button onclick="copyText(this)">Copy</button></td>
  </tr>
</table>
Bharata
  • 11,779
  • 6
  • 27
  • 42
  • This answer would be more useful for inexperienced coders if explained what your code does. Some comments in the code would be useful as would a brief summary of what you are doing. I know why you add an input, but it may not be obvious to others. – Jon P Sep 04 '18 at 22:58