0

I have a table in my web page. i write a code to copy td text to clipboard with a button. when i click the button td text copied to clipboard with break lines. how can i copy td text without break lines?

Html code:

<table>
                                
   <tr role="row">
      <th style="padding-right: 8px;">copy</th>
      <th style="padding-right: 8px;">phone</th>
   <tr/>

   <?php foreach ($all as $all_items) {?>
      <tr>
         <td>
         <button class="btn-copy" type="button" >copy</button>
         </td>

         <td>
             <?php if (isset($all_items['phone'])) echo $all_items['phone']; ?>
         </td>

      <tr/>
   <?php } ?>

</table>

my javascript code:

$(".btn-copy").click(function() {

    let tmpElement = $('<textarea style="opacity:0;"></textarea>');
    let parent = $(this).closest('td').siblings().not(':last').each(function(){
        tmpElement.text(tmpElement.text() + $(this).text() + '\t');            
    });
    
    tmpElement.appendTo($('body')).focus().select();
    document.execCommand("copy");
    tmpElement.remove();
});
Farid
  • 158
  • 1
  • 2
  • 13

2 Answers2

0

One way could be to erase the new line characters from the content before copying it.

.replace(/(\r\n|\n|\r)/gm," ");

i.e:

$(".btn-copy").click(function() {

    let tmpElement = $('<textarea style="opacity:0;"></textarea>');
    let parent = $(this).closest('td').siblings().not(':last').each(function(){
        tmpElement.text(tmpElement.text() + $(this).text() + '\t');    

        // Strip newlines
        tmpElement.text(tmpElement.text().replace(/(\r\n|\n|\r)/gm," "));        
    });
    
    tmpElement.appendTo($('body')).focus().select();
    document.execCommand("copy");
    tmpElement.remove();
});

PatricNox
  • 3,306
  • 1
  • 17
  • 25
  • i'm quite unsure about the tmpElement.text() part though, if it's correctly written. I'm not someone who prefers jquery. – PatricNox Sep 08 '20 at 09:30
0

Some times I want my Copy functions to keep the line breaks, while other times I need the line breaks not to be copied.

This JavaScript function does not copy line breaks:

    <script>
function copy(that){
  var inp =document.createElement('input');
  document.body.appendChild(inp)
  inp.value =that.textContent
  inp.select();
  document.execCommand('copy',false);
  inp.remove();
}
    </script>    

You can use it by simply editing your code to:

<td onClick="copyThis">    

Then you will be able to copy all your text on your element without its line breaks, by simply clicking on it, without the need of a button.

This is also helpful when you have many different elements you may need to copy, because this way you need no buttons and no additional code for each button to copy each element.

rx65m
  • 105
  • 6