简体   繁体   中英

Copy ( to clipboard ) only one required column contents of html data table

My requirement is simple.
I have a table with four columns. Have some mobile numbers in 2nd column "Mobile No.". I just want to copy ( to clipboard ) All the mobile numbers in the " Mobile No. " column on button click.
Tried some javascript samples for the same, not worked as required. Please give some suggestions.

<html>
<head>
<style>
table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 100%;
}

td, th {
  border: 1px solid #dddddd;
  text-align: left;
  padding: 8px;
}

tr:nth-child(even) {
  background-color: #dddddd;
}
</style>
</head>
<body>

<h2>HTML Table</h2>

<button id="copy-table-button" data-clipboard-target="#datatable">  Copy Mobile No. </button>
  
<table id="myTable">
 <thead>
   <tr>
    <th>Sl No</th>
    <th>Mobile No.</th>
    <th>Name</th>
    <th>Status</th>
   </tr>
  </thead>
  <tbody>
  <tr>
    <td>1</td>
    <td>1234567890</td>
    <td>Maria</td>
    <td>Active</td>
  </tr>
  <tr>
    <td>2</td>
    <td>2223330</td>
    <td>Ruma</td>
    <td>Active</td>
  </tr>
    <tr>
    <td>3</td>
    <td>3334440</td>
    <td>Kumar</td>
    <td>Not-Active</td>
  </tr>
    <tr>
    <td>4</td>
    <td>44455500</td>
    <td>Subba</td>
    <td>Active</td>
  </tr>
    <tr>
    <td>5</td>
    <td>555666111</td>
    <td>Orayyo</td>
    <td>Not-Active</td>
  </tr>
    <tr>
    <td>6</td>
    <td>555666111</td>
    <td>Orayyo</td>
    <td>Active</td>
  </tr>
    <tr>
    <td>7</td>
    <td>555666111</td>
    <td>Orayyo</td>
    <td>Not-Active</td>
  </tr>
  
  </tbody>
</table>

</body>
</html>

I just need to copy them as plain text, to paste in other websites or forms. Should paste like this after copy..

1234567890
2223330
3334440
44455500
555666111
555666111
555666111

Thanks in advance.

This works for me, let me know if you have any troubles with it:

const copyButton = document.querySelector('#copy-table-button');

const copyToClipboard = (_) => {
  const dataElements = document.querySelectorAll('tr > td:first-child + td');
  const data = Array.from(dataElements).map(element => element.textContent).join('\n');
  const blob = new Blob([data], {type: 'text/plain'});
  const clipboardItem = new ClipboardItem({'text/plain': blob});

  navigator.clipboard.write([clipboardItem]);
}

copyButton.addEventListener('click', copyToClipboard);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM