Copy table cell by clicking button

Asked

Viewed 323 times

1

I am developing a system and I need each button to copy its information, but I am having problems with the command select() and document.execCommand("copy") as you can see in the image, where is my mistake?

  $(function() {
    $(".btn").click(function(){
      var x = $(this).parent().parent().find(':nth-child(1)').html()
      console.log(x);
      x.select();
      document.execCommand("copy");
    });
  });

erros

  • The mistake says x.select is not a function review code on line 197 of the page revendedor

1 answer

1


First of all, there’s no way .select() in an HTML code. You can only use the method .select() in form elements (input, select, textarea etc.)

The error is because you are selecting HTML (.html()) of an element and trying to use the method .select() in HTML. The HTML of an element is not an element, so it cannot use the method. And even if it was an element (other than a form element, as mentioned above), nothing will occur (nothing will be selected or copied).

See the difference when you select and copy the value of a field input:

$(function() {
    $(".btn").click(function(){
      var x = $(this).parent().parent().find(':nth-child(1)');
      //console.log(x);
      x.select();
      document.execCommand("copy");
    });
  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Clique em um botão e dê CTRL+V. Irá colar o mesmo texto do campo:
<table>
   <tr>
      <td>
         <input type="text" value="código">
      </td>
      <td>
         <button class="btn">Botão</button>
      </td>
   </tr>
   <tr>
      <td>
         <input type="text" value="código2">
      </td>
      <td>
         <button class="btn">Botão</button>
      </td>
   </tr>
</table>

  • then there is no way to copy the table value with Document.execCommand("") ?

  • I think there’s a way, but not using .select(). You can ask another question like "how to copy text from a table cell" if there is no question already asked about it.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.