Copy table to clipboard in vue.js

Viewed 1519

I am trying to copy div element to clipboard in vuejs. I have gone through to search related solution and applied. But not working. I ant to copy full table to clipboard. Thanks in advance

 <button v-on:click = "copyToClipboard(select_txt)">Click To Copy</button>
                <table class="table table-sm" id="select_txt">
                    <tr>
                        <td>Name</td>
                        <td> abcd </td>
                    </tr>
                    <tr>
                        <td>Phone</td>
                        <td>124545</td>
                    </tr>
                </table>

Methods

 methods:{
        copyToClipboard(containerid){
            var range = document.createRange();
            range.selectNode(containerid); 
            window.getSelection().removeAllRanges();
            window.getSelection().addRange(range);
            document.execCommand("copy");
            window.getSelection().removeAllRanges();
            alert("data copied");
        }
    },
1 Answers

You are doing something wrong in selecting node.

copyToClipboard(containerid){
            var range = document.createRange();
            let containerNode = document.getElementById(containerid); //// this part
            range.selectNode(containerNode); //// this part
            window.getSelection().removeAllRanges();
            window.getSelection().addRange(range);
            document.execCommand("copy");
            window.getSelection().removeAllRanges();
            alert("data copied");
        }

To copy html code

copyToClipboard(containerid) {
      let containerNode = document.getElementById(containerid);
      var textArea = document.createElement("textarea");
      textArea.style.position = "fixed";
      textArea.style.top = 0;
      textArea.style.left = 0;

      // Ensure it has a small width and height. Setting to 1px / 1em
      // doesn't work as this gives a negative w/h on some browsers.
      textArea.style.width = "2em";
      textArea.style.height = "2em";

      // We don't need padding, reducing the size if it does flash render.
      textArea.style.padding = 0;

      // Clean up any borders.
      textArea.style.border = "none";
      textArea.style.outline = "none";
      textArea.style.boxShadow = "none";

      // Avoid flash of white box if rendered for any reason.
      textArea.style.background = "transparent";

      textArea.value = containerNode.outerHTML;

      document.body.appendChild(textArea);
      textArea.focus();
      textArea.select();
      document.execCommand("copy");
      window.getSelection().removeAllRanges();
      document.body.removeChild(textArea);
      alert("data copied");
    }
Related