最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to copy the text of html table to clipboard? - Stack Overflow

programmeradmin0浏览0评论

I am binding the data to html table by using angularjs functionality in separate .js file. Where as I want to copy these bounded text data and paste it to any text document by clicking the input button below.

<button type="button" class="btn" ng-click="selectElementContents();"></button>

and in angular controller written function as below..

$scope.selectElementContents = function () {
        copyTblData();        
    }
function copyTblData() {
        var copyText = document.getElementById('tablerecords');
        $('#tablerecords').focus();
        $('#tablerecords').select();
        document.execCommand('copy');            
    }

where I am doing mistake not understandable, required suggestion is appreciated.

I am binding the data to html table by using angularjs functionality in separate .js file. Where as I want to copy these bounded text data and paste it to any text document by clicking the input button below.

<button type="button" class="btn" ng-click="selectElementContents();"></button>

and in angular controller written function as below..

$scope.selectElementContents = function () {
        copyTblData();        
    }
function copyTblData() {
        var copyText = document.getElementById('tablerecords');
        $('#tablerecords').focus();
        $('#tablerecords').select();
        document.execCommand('copy');            
    }

where I am doing mistake not understandable, required suggestion is appreciated.

Share Improve this question asked Oct 23, 2018 at 18:31 abbasabbas 531 silver badge3 bronze badges 2
  • Is your table selected? – Poul Bak Commented Oct 23, 2018 at 18:54
  • no, its not getting selecting even. – abbas Commented Oct 23, 2018 at 18:56
Add a ment  | 

1 Answer 1

Reset to default 4

For select data , you must use ranges and select. You can try it:

let table = document.querySelector('#testTable');
let button = document.querySelector('#button');
function selectNode(node){
  let range  =  document.createRange();
  range.selectNodeContents(node)
  let select =  window.getSelection()
  select.removeAllRanges()
  select.addRange(range)
}
button.addEventListener('click',function(){
  selectNode(table);
  document.execCommand('copy')
  
})
td{
   border:1px solid black;
}
<table collapsed id = 'testTable'>
 <tr>
   <td>test</td>
    <td>test</td>
  </tr><tr>
   <td>test</td>
    <td>test</td>
  </tr>
</table>
<br/>
<button id = "button">select</button>

发布评论

评论列表(0)

  1. 暂无评论