I have a table with various columns, and I want the user to be able to copy text in a cell by clicking on it. This is dynamic content, so I don't know what the ID or class will be at the time.
This works for me, but it will obviously not work because of getElementById
. How could I do it so the copy works for the cell the use clicks on?
function copyAddress() {
/* Get the text field */
var copyText = document.getElementById("address");
/* Select the text field */
copyText.select();
copyText.setSelectionRange(0, 99999); /* For mobile devices */
/* Copy the text inside the text field */
navigator.clipboard.writeText(copyText.value);
}
CodePudding user response:
Hi if you wanted to copy the text on dynamic table you'll need to select the element first. since you're unsure if what's the class/id you should just select the html element
let's say i have this table and i wanted to select all inside text inside td
<table >
<tr>
<th>Company</th>
<th>Contact</th>
<th>Country</th>
</tr>
<tr>
<td>Alfreds Futterkiste</td>
<td>Maria Anders</td>
<td>Germany</td>
</tr>
<tr>
<td>Centro comercial Moctezuma</td>
<td>Francisco Chang</td>
<td>Mexico</td>
</tr>
</table>
you could do on javascript is
let content = document.querySelectorAll('table tr td'); // All td will be selected and will be added to NodeList
after that you'll want to convert that nodelist into array.
let contentArr = Array.from(content) // you can use Array.from
then just loop through all the elements you have and for each one add an event listener (click) then get the innerText and copy it to the clipboard. you can check it here Hope it helps
contentArr.forEach((element) => {
element.addEventListener("click", (e) => {
let copyText = e.target.innerText
navigator.clipboard.writeText(copyText);
});
});
EDIT: i saw on one of comments that this is how you detect the click
if that's the case is the onclick function adding automatically on the div you wanted to be selected? if yes
what you can do is
<div onclick="copyAddress(this)">
add this keyword inside your function
now what you can do on javascript is
function copyAddress(e) {
navigator.clipboard.writeText(e.innerText); // the e is the current element and just get the innerText and copy it to clipboard.
}
EDIT:
if this is your format
<div onclick="copyAddress(this)"><textarea>text to copy</textarea></div>
function copyAddress(e) {
const copyText = e.firstChild;
copyText.select();
copyText.setSelectionRange(0, 99999);
navigator.clipboard.writeText(copyText.value);
}
CodePudding user response:
I assume you mean the class name would be different? If so, you could put the dynamic class inside of a static div that won't change. That might work.
function copyAddress() {
let childItem = document.getElementById("parentDivName").firstElementChild;
/* Obviously you would tweak this to work for you, this is just an idea */
}