Reputation: 1
I'm fairly new to Javascript. I would like to create the following:
Example:
"Cell1" is clicked. This will be copied to clipboard: "Cell2 - Cell3".
I have been trying for hours but can't quite figure out the JS.
Thank you in advance for your help.
Example table:
<html>
<body>
<table>
<tr>
<th>Column1</th>
<th>Column2</th>
<th>Column3</th>
<th>Column4</th>
</tr>
<tr>
<td>Cell1</td>
<td>Cell2</td>
<td>Cell3</td>
<td>Cell4</td>
</tr>
</table>
</body>
</html>
Upvotes: 0
Views: 923
Reputation: 1
<div>
<input type = "text" id="txt">
<input type = "button " id ="btn" value ="copy" onclick="copyTxt('txt')">
</div>
<div>
<input type = "text" id="txt1">
<input type = "button " id ="btn1" value ="copy" onclick="copyTxt('txt1')">
</div>
<div>
<input type = "text" id="txt2">
<input type = "button " id ="btn2" value ="copy" onclick="copyTxt('txt2')">
</div>
<script>
function copyTxt(id){
document.getElementById(id).select();
document.execCommand('copy');
}
</script>
Upvotes: 0
Reputation: 582
You can try like this, it is a bit newish javascript.
I used filter and reduce array functions
const cells = [...document.querySelectorAll('tr td')]
function getOtherCells(e) {
const otherCells = cells.filter(cell => e.target !== cell);
const text = otherCells.reduce((acc, cell, idx) => {
return idx===0? `${cell.innerText}`:`${acc} - ${cell.innerText}`;
}, "");
console.log(text)
}
cells.forEach(cell => cell.addEventListener("click", getOtherCells))
th, td {
border: 1px solid black;
}
<html>
<body>
<table>
<tr>
<th>Column1</th>
<th>Column2</th>
<th>Column3</th>
<th>Column4</th>
</tr>
<tr>
<td>CellOne</td>
<td>CellTwo</td>
<td>CellThree</td>
<td>CellFour</td>
</tr>
</table>
</body>
</html>
Welcome on board and I hope this helped :)
Upvotes: 0