Button and JS, Copy Field to Clipboard

talkinggoat

Member
I needed a way to copy a field to the clipboard, using a button, so here is how I did it...

Use the button element plugin to create a button. Call it whatever you want.
In the JavaScript of the button, create a new script.
Set the event to Click.
Here is the code:
JavaScript:
var copyText = document.getElementById("user_data___volunteer_unique_home_url");
var textArea = document.createElement("textarea");
textArea.value = copyText.textContent;
document.body.appendChild(textArea);
textArea.select();
document.execCommand("Copy");
alert("Copied the text: " + textArea.value);
textArea.remove();

Leave the rest set to default.
Save and profit.

I am no JS expert, but, from what I can gather, most of the button scripts work by grabbing text from the DOM element "textarea". Since the output of a field is a <div>, texArea.select() will not work. It throws an error.

I think this is what it's doing. I'm just starting out in JS, so I'm not 100% sure.
Line 1 tells JS what you want to select, by ID. This is the tablename___fieldname.
Line 2-4 Converts the area into <textarea> and gets it ready to copy.
Line 5 Selects the text.
Line 6 Performs the copy.
Line 7 Produces a message box saying the area was copied.
Line 8 Removes "textarea".
 
Last edited:
We are in need of some funding.
More details.

Thank you.

Members online

Back
Top