I am debugging someone else's code and the "copy" function works the first time it is clicked, but for any subsequent attempt it needs to be clicked twice for it to copy. I cannot figure out what is causing this.
Each node is selected by ticking the boxes that the user wants to copy and then clicking "copy". The copied data can then be pasted into Excel or similar.
HTML:
<li id="copy">
<a title="Copy Contents Of Records" data-source="dbTable" href="#" ng-click="copyRow($event)" ng-class="{'disabled' : ShowLoading}"><i class="fa fa-paste"></i></a>
</li>
JAVASCRIPT:
$scope.copyRow = function ($event) {
$event.preventDefault();
let head = [];
angular.forEach($scope.data.objColumns,
function (col) {
head.push(col.strColumnName);
});
let rows = [];
angular.forEach($scope.data.objColumnData,
function (item) {
if (item.bolSelected) {
let row = [];
angular.forEach(item.columnData,
function (data) {
row.push(data.strColumnDisplayValue);
});
rows.push(row);
}
});
let virtualTable = document.createElement('table');
virtualTable.id = "virTab";
// For table head
for (let i = 0; i < head.length; i++) {
let th = document.createElement('th');
th.innerHTML = head[i];
virtualTable.appendChild(th);
}
// For table body
for (let i = 0; i < rows.length; i++) {
console.log(rows[i]);
let tr = document.createElement('tr');
for (let j = 0; j < rows[i].length; j++) {
let td = document.createElement('td');
td.innerHTML = rows[i][j];
td.removeAttribute('style');
tr.appendChild(td);
}
tr.removeAttribute('style');
virtualTable.appendChild(tr);
}
virtualTable.removeAttribute('style');
document.body.appendChild(virtualTable);
// Invoke copying function
let textRange;
if (isIE()) {
textRange = document.body.createTextRange();
textRange.moveToElementText(document.getElementById('virTab'));
textRange.execCommand("copy");
} else {
textRange = document.createRange();
textRange.selectNode(document.getElementById('virTab'));
window.getSelection().addRange(textRange);
const success = document.execCommand('copy');
let msg = success ? 'Success' : 'Failure';
console.log(msg);
window.getSelection().removeAllRanges();
}
The issue was that the selection needed to be cleared before the:
textRange.selectNode(document.getElementById('virTab'));
The solution was to add
window.getSelection().removeAllRanges();
to the beginning of the 'else' statement.