일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
- javascript
- Emulator
- url parsing
- module
- jquery
- Front-End
- html
- Javasript
- DataTable
- node.js
- React
- Cloud
- jstree
- EJS
- ajax
- Frontend
- node
- Excel
- innerText
- json
- CSS
- Express
- vue
- Video
- password
- insertAdjacentHTML
- github
- QueryString
- Today
- Total
Developer's blog
[JavaScript] Copy 버튼을 통해 DataTable 내의 데이터 내용 Copy 하기 본문
지금 개발하고자 하는 Copy 기능은 요즘 어디서든 찾아볼 수 있는 기능이다.
이는, 바로 텍스트 옆에 복사 버튼이 있고, 그것을 클릭한다면 옆의 텍스트가 복사되는 기능이다.
이를 위해서 처음은 Javascript에서 주로 쓰이는 Text를 Clipboard로 복사하는 방법을 찾아보았다.
그 결과, https://sub0709.tistory.com/144님의 블로그를 찾을 수 있었고 JavaScript에서 쓰는 텍스트 복사 방법을 알 수 있었다.
이를 적용시키기 위하여 내가 현재 작성한 DataTable의 Code는 다음과 같다.
function initTable() {
table = $('.dataTables-example').DataTable({
serverSide: true,
processing: true,
ajax: {
url: HOST + "/api/admin/exchange",
type: "GET",
dataType: "json",
contentType: 'application/json; charset=utf-8',
data: function (d) {
const info = $('.dataTables-example').DataTable().page.info();
d.length = info.length;
d.startDate = startDate + " 00:00:00";
d.endDate = endDate + " 23:59:59";
d.page = parseInt(info.page) + 1
const select = $("#selectOption").val();
const searchText = $("#searchText").val();
if (searchText !== "") {
d.selectOption = select;
}
if (select !== "-1") {
d.searchText = searchText
}
},
dataSrc: function (data) {
//const data = res.message.data;
data.recordsTotal = data.Message.RecordTotalCount;
data.recordsFiltered = data.Message.RecordTotalCount;
data.data = data.Message.AdminInfo;
if (data.Message.AdminInfo === null) {
return []
}
return data.data;
}
},
pageLength: 10,
responsive: true,
searching: false, // 검색 기능 숨기기
ordering: false, // 정렬 기능 숨기기
/*dom: '<"html5buttons"B>lTfgitp',
buttons: [
{ extend: 'copy' },
{ extend: 'csv' },
{ extend: 'excel', title: 'ExampleFile' },
{ extend: 'pdf', title: 'ExampleFile' },
{ extend: 'print',
customize: function (win){
$(win.document.body).addClass('white-bg');
$(win.document.body).css('font-size', '10px');
$(win.document.body).find('table')
.addClass('compact')
.css('font-size', 'inherit');
}
}
],*/
columnDefs: [
{
"targets": 0, // your case first column
"className": "text-center", // center, right, left
//"width": "4%"
},
{
"targets": 1,
"className": "text-center",
},
{
"targets": 2,
"className": "text-center",
},
{
"targets": 3,
"className": "text-center",
},
{
"targets": 4,
"className": "text-center",
},
{
"targets": 5,
"className": "text-center",
},
{
"targets": 6,
"className": "text-center",
},
{
"targets": 7,
"className": "text-center",
}
],
columns: [
{
"data": null, "sortable": false,
render: function (data, type, row, meta) {
return meta.row + meta.settings._iDisplayStart + 1;
}
},
{
"data": "TransactionId", render: function (data, type, row, meta) {
return "<span id='txID'>" + data + "</span>" + "   " +
"<button type='button' class='btn btn-primary btn-xs' id='copyButton'>Copy</button>"
}
},
{"data": "AdminName"},
{"data": "AgencyName"},
{
"data": "Cash",
render: function (data, type, row, meta) {
return data.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}
},
{
"data": "ExchangeCash",
render: function (data, type, row, meta) {
return data.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}
},
{"data": "Rate"},
{
"data": "RegDate",
render: function (data, type, row, meta) {
return convertTime(data);
}
},
/*{
"data": null,
"defaultContent":
"<button type='button' class='btn btn-info btn-xs' id='edit' style='width: 60px'>Edit</button>   " +
"<button type='button' class='btn btn-danger btn-xs' id='delete' style='width: 60px'>Danger</button>"
}*/
]
});
}
나는 여기서
{
"data": "TransactionId", render: function (data, type, row, meta) {
return "<span id='txID'>" + data + "</span>" + "   " +
"<button type='button' class='btn btn-primary btn-xs' id='copyButton'>Copy</button>"
}
},
span id='txID'의 값을 가져와 복사하고 싶으므로 처음에
var copyText = document.getElementById("txID");
copyText.select();
copyText.setSelectionRange(0, 99999); /*For mobile devices*/
document.execCommand("copy");
alert("Copied the text: " + copyText.value);
이를 이용하여 복사하려 했으나 copyText.select is not a function이라는 에러를 만나게 되었다..ㅠㅠ
이에 대해 생각을 해본 결과로는 DataTable내의 값이라 id값을 못 받아오는 것은 아닌가..라는 생각을 하였다.
따라서 "그럼 DataTable내의 id 값은 어떻게 가져오지?"라고 생각을 하여 검색을 해보았는데 아쉽게도 방법을 찾기에는 역부족이었다.
그래서 "그럼 id값이 아닌 Text를 읽어 복사하는 것은 어떨까?"라고 생각하여 찾아보던 중 https://stackoverflow.com/questions/50795042/create-a-copy-button-without-an-input-text-box/50795833 참고된 StackOverFlow에 올라와있던 질문 중 23 답을 통해 해결법을 찾을 수 있었다.
따라서 동일하게 텍스트를 복사할 수 있는 새로운 함수를 아래와 같이 하나 만들어주었다.
function Clipboard_CopyTo(value) {
var tempInput = document.createElement("input");
tempInput.value = value;
document.body.appendChild(tempInput);
tempInput.select();
document.execCommand("copy");
document.body.removeChild(tempInput);
}
이후 이 함수를 이용하기에 앞서, rowData를 통해 해당 열의 정보를 가져오고 그중 TransactionID를 가져오는 Code를 통해 복사하기 원하는 텍스트의 정보를 가져올 수 있었다.
$('.dataTables-example').on('click', '#copyButton', function () {
const row = $(this);
const tr = row.closest('tr');
const dataTableRow = table.row(tr[0]);
const rowData = dataTableRow.data();
Clipboard_CopyTo(rowData.TransactionId)
alert('Copy');
});
이를 통해 DataTable 내의 Text를 가져와 복사하는 기능을 만들어 볼 수 있었다!!!
'FrontEnd > JavaScript' 카테고리의 다른 글
[JavaScript] jsTree 사용법 예제 모음 (0) | 2021.07.02 |
---|---|
[JavaScript] 클릭 시, 새 창으로 결과 출력 (0) | 2021.06.29 |
[JavaScript] $.each() 사용법 정리 (0) | 2021.06.22 |
[JavaScript] 파라미터 값 다른 페이지로 렌더링 & URL Parsing (0) | 2021.06.17 |
[JavaScript] Form Input Box에 , 자동 생성 기능 개발 (0) | 2021.06.17 |