1

I am using this reference to copy my table(paginated) to clipboard- Select a complete table with Javascript (to be copied to clipboard) But the problem I am facing here is, it is just copying the first page data. I need all the rows to be copied, irrespective of which page I am on. I am using this in an angular application. Kindly provide me a work around for this.

1 Answers1

4

It can be done by JavaScript only.

It can be done in two step:

Step 1 : Select table get using selection command

Step 2 : Apply clipboard using document.execCommand("copy");

Please check below :

 function selectElementContents(el) {
        var body = document.body, range, sel;
        if (document.createRange && window.getSelection) {
            range = document.createRange();
            sel = window.getSelection();
            sel.removeAllRanges();
            try {
                range.selectNodeContents(el);
                sel.addRange(range);
            } catch (e) {
                range.selectNode(el);
                sel.addRange(range);
            }
            document.execCommand("copy");

        } else if (body.createTextRange) {
            range = body.createTextRange();
            range.moveToElementText(el);
            range.select();
            range.execCommand("Copy");
        }
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<table id="tableId">
    <thead>
        <tr><th>Heading 1</th><th>Heading 2</th></tr>
    </thead>
    <tbody>
        <tr><td>cell 1</td><td>cell 2</td></tr>
        <tr><td>cell 3</td><td>cell 4</td></tr>
    </tbody>
</table>

<input type="button" value="select table"
   onclick="selectElementContents( document.getElementById('tableId') );">

Now Ctrl+V paste clipboard value as per your requirement

saAction
  • 2,035
  • 1
  • 13
  • 18
  • Thanks @saAction, I am doing the same thing, but I have a problem with paginated table, as in, If I have 20 rows, the data being paginated by 10 values per page and I am seeing the first page data, only that data is getting copied. But I need to copy all the 20 rows, irrespective of its visibility. – Sanskriti Routray Aug 28 '18 at 17:12
  • In this case you can crate a hidden table (not visible on screen for user) without pagination and use it into clipboard function OR you can remove pagination before using copy command and apply it again after completed clipboard function – saAction Aug 28 '18 at 17:25
  • Thanks, I took the approach that you suggested. And it Worked. – Sanskriti Routray Aug 29 '18 at 04:59
  • This is one of the best solution for copying tables. Thanks a lot! Just wondering why you import jQuery? – G M Sep 19 '22 at 11:04