19

I have write javascript to select the table but I want to now automaticaly copy it after the click of the button.Please help me.My javascript is like this.

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);
                    document.execCommand('Copy');
                } 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');

            }
        }
RKS
  • 591
  • 2
  • 5
  • 6
  • 1
    possible duplicate of [Copy to the clipboard in JavaScript?](http://stackoverflow.com/questions/400212/copy-to-the-clipboard-in-javascript) – Software Engineer Jan 09 '15 at 22:03
  • 1
    Credit: The code here and in one of the answers appears to have been taken from: https://stackoverflow.com/a/2044793/943435 by @TimDown. See the original for his working example. – Yogi May 20 '18 at 01:04
  • In IE: `window.clipboardData.setData("text", el.outerHTML);` – Andrew Jun 08 '18 at 20:17

10 Answers10

22
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);
    }
} else if (body.createTextRange) {
    range = body.createTextRange();
    range.moveToElementText(el);
    range.select();
}
document.execCommand("Copy");}
Dio
  • 229
  • 2
  • 3
  • Note that [document.createRange](https://developer.mozilla.org/en-US/docs/Web/API/Document/createRange) and [window.getSelection](https://developer.mozilla.org/en-US/docs/Web/API/Window/getSelection) are supported in all modern browsers, and even IE9+. Most web applications probably do not need the fallback anymore. – Don McCurdy Dec 20 '19 at 22:36
11

Try this:

<script type="text/javascript">

function copytable(el) {
    var urlField = document.getElementById(el)   
    var range = document.createRange()
    range.selectNode(urlField)
    window.getSelection().addRange(range) 
    document.execCommand('copy')
}

</script>

<input type=button value="Copy to Clipboard" onClick="copytable('stats')">

<table id=stats>
    <tr>
        <td>hello</td>
    </tr>
</table>
Niente0
  • 504
  • 3
  • 11
10

I know this is an old one, but if any one still looking for a solution. this one worked for me

    <script>
    $(document).ready(function() {
        $("#copyBtn").on("click",
            function(e) {
                copyTable("listTable", e);
            });

    });

    function copyTable(el, e) {
        e.preventDefault();
        var table = document.getElementById(el);
        
        if (navigator.clipboard) {
            var text = table.innerText.trim();
            navigator.clipboard.writeText(text).catch(function () { });
        }
    }
</script>
Craig Walker
  • 394
  • 4
  • 9
  • Nice and easy, and still very useful, Thank you. Although `table.outerHTML` would be more appropriate, if one needed the table structure, for example to copy the table to Excel. – BurninLeo Jul 31 '23 at 20:45
6
  • This has worked for me, it is not only restricted to table, but it can even select and copy to clipboard all elements inside Node specified with id.

  • I have tested in Mac Chrome as well as windows chrome.

  • Usescase : Copy Signature created by Signature Generator based on JS

Demo :

<div id="signature_container">
  <p id="company_name" style="margin-top: 4px; margin-bottom: 0px; color: #522e64; font-weight: 700; font-size: 16px; letter-spacing: 1px; border-bottom: solid 2px #522e64; width:250px; padding-bottom: 3px;">The Company Name</p>
  <p style="margin-top: 4px; margin-bottom: 0px; color: #00706a; font-weight: 700; font-size: 15px;"> <span id="first_name_output_2"></span>Firstname<span id="last_name_output_2"> Lastname</span>&nbsp;&nbsp;&nbsp;&nbsp;<span id="designation_output_2" style="color: #000000; font-weight: 500; font-size: 15px;">Designation</span></p>
  <p style="margin-top: 0px; margin-bottom: 0px; color: #625469; font-weight: normal; font-size: 15px; letter-spacing: 0.6px;">youreamil@xyz.com<span id="email_output_2"></span>&nbsp;&nbsp;&nbsp;</p>
</div>
<br><br>
<input type="button" onclick="selectElementContents( document.getElementById('signature_container') );" value="Copy to Clipboard">

<script>
  function selectElementContents(el) {
    var body = document.body,
      range, sel;
    if (document.createRange && window.getSelection) {
      range = document.createRange();
      sel = window.getSelection();
      sel.removeAllRanges();
      range.selectNodeContents(el);
      sel.addRange(range);
    }
    document.execCommand("Copy");
  }
</script>
krupesh Anadkat
  • 1,932
  • 1
  • 20
  • 31
1

UPDATE

Use this code instead.

Code:

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);
        }
    } else if (body.createTextRange) {
        range = body.createTextRange();
        range.moveToElementText(el);
        range.select();
        document.execCommand("copy");
    }
}
<input type="button" value="select table"
  onclick="selectElementContents( document.getElementById('table') );">
  
<table id="table">
    <thead>
        <tr><th>Heading</th><th>Heading</th></tr>
    </thead>
    <tbody>
        <tr><td>cell</td><td>cell</td></tr>
    </tbody>
</table>
Community
  • 1
  • 1
vitorio
  • 329
  • 1
  • 3
  • 18
  • How to use that plugin? – RKS Sep 26 '14 at 07:14
  • Is there not any solution without using plugin? – RKS Sep 26 '14 at 07:23
  • 14
    This code just selects the whole table but it doesnot copy it. – RKS Sep 26 '14 at 07:41
  • 1
    @vitorio : I have tried to copy the hidden table. Do you have any idea about hidden table – mahesh Jun 20 '18 at 16:37
  • Note that [document.createRange](https://developer.mozilla.org/en-US/docs/Web/API/Document/createRange) and [window.getSelection](https://developer.mozilla.org/en-US/docs/Web/API/Window/getSelection) are supported in all modern browsers, and even IE9+. Most web applications probably do not need the fallback anymore. – Don McCurdy Dec 20 '19 at 22:36
  • @RKS just duplicate the `document.execCommand("copy");` line that's in the `else if` condition block into the bottom of the `if` condition block. – Smithee Jun 15 '22 at 14:34
1

The previous scripts did not work for me because the .execCommand("Copy") was not triggering. By attaching it to the document itself, and moving it outside of the conditional, I was able to get it to work:

I think this function is more robust:

  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);
        }
    } else if (body.createTextRange) {
        range = body.createTextRange();
        range.moveToElementText(el);
        range.select();
    }
    document.execCommand("Copy");
}
R Brewer
  • 19
  • 1
1

All answers using execCommand are deprecated.

The correct answer is using Clipboard API, as described by user Craig Walker in an answer to this question, above. Click here to go to the answer.

OP, please update this post and mark Craig's answer as correct.

0

by using a library called clipboard.js making it much easier. for more info, check: https://webdesign.tutsplus.com/tutorials/copy-to-clipboard-made-easy-with-clipboardjs--cms-25086

<script src="//cdnjs.cloudflare.com/ajax/libs/clipboard.js/1.4.0/clipboard.min.js">
(function(){
    new Clipboard('#copy-table-button');
})();
</script>

<button class="btn" id="copy-table-button" data-clipboard-target="#table_results">Copy</button>
               

<table id='table_results' >

</table>
David Pratt
  • 703
  • 7
  • 16
penny chan
  • 769
  • 1
  • 10
  • 15
0

You can use this custom script, if you need to copy to clipboard all data from table; html:

<button class='btnclipboard' data-source='tableStudents'> Copy table </button>

<table id="tableStudents">
<thead>
 <th> user_id </th>
 <th> Name </th> 
</thead> 
<tbody>
 <tr>
  <td> 123 </td>
  <td> Proba </td>
 </tr>
<tbody>
</table>

<script>
    $('.btnclipboard').click(function(e) {
    e.preventDefault();
        copyTableToClipboard($(this).data('source'));
});

function copyTableToClipboard() {


var clipboard=new Clipboard('.btnclipboard',{

    text: function(trigger) {

        var txt=[];
                var headColumns = [];
                $("#tableStudents th").each(function(){
                    var textColumn = $(this).text();
                    if(textColumn == null || textColumn == "") {
                        textColumn = $(this).attr('title');
                    }
                    if(textColumn == undefined || textColumn == null) {
                        textColumn = "";
                    }
                    headColumns.push(textColumn);
                    // console.log($(this).text());
                });
                console.log('headColumns', headColumns);
                var head=headColumns;
                txt.push(head.join("\t"));

                var rowColumns=[];
                $("#tableStudents tr").each(function(){
                    var row=[];
                    $(this).find('td').each(function(){
                        var textColumn = $(this).text();
                        if($(this).find("i").hasClass('fa-check')){
                            textColumn = "1";
                        }
                        // if(textColumn == "") {
                        //  // textColumn = $(this).attr('title');
                        //  textColumn = "";
                        // }
                        // if(textColumn != null) {
                            row.push(textColumn);
                        // }
                    //console.log($(this).text());
                    });
                    if(row.length > 0) {
                        rowColumns.push(row);
                        txt.push(row.join("\t"));
                    }
                });
                console.log('rowColumns', rowColumns);
                return txt.join("\n");
    }


});

clipboard.on('success', function(e) {

    console.info('Action:', e.action);
    e.clearSelection();

    if (Notification.permission == "granted")
    {
        var notification = new Notification('Data copied to clipboard', {
            icon: '../dist/img/favicon.png',
            body: "You can now paste (Ctrl+v) into your favorite spreadsheet editor !"
        });
    }else{
        console.warn(Notification.permission);
    }
});

clipboard.on('error', function(e) {
    console.error('Action:', e.action);
    console.error('Trigger:', e.trigger);
});
}
</script>

After you click on the button, your table data should be copied.

Svetoslav
  • 127
  • 1
  • 3
-1
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);
    }
} else if (body.createTextRange) {
    range = body.createTextRange();
    range.moveToElementText(el);
    range.select();





}
CopiedTxt = document.selection.createRange();
CopiedTxt.execCommand("Copy");}
alpc
  • 598
  • 3
  • 6