Reputation: 83
so i was trying to make a button that when clicked it copy a value from a variable
like
<button onclick="copyToClipboard()">COPY</button>
and then on that function it takes the element to copy from a variable like
var copyids = {
"ids": [
{
"name": "id1",
"id": 192389021
},
{
"name": "id2",
"id": 123879032
},
{
"name": "id3",
"id": 149018292
},
]
};
so like copyids.ids[0].id
and it copy that value
i hope its understandable
Upvotes: 1
Views: 5103
Reputation: 8706
The execCommand
method has been deprecated, and it might not be supported by newer releases.
However, there is a Clipboard API that you can use in it's place.
To let the user select what to copy from your list:
<button onclick="copyToClipboard()">COPY</button>
<select>
<option value="id1">id1</option>
<option value="id2">id2</option>
<option value="id3">id3</option>
</select>
Then your function can work like this:
function copyToClipboard() {
var copyids = {
ids: [
{
name: "id1",
id: 192389021,
},
{
name: "id2",
id: 123879032,
},
{
name: "id3",
id: 149018292,
},
],
};
let selectedIndex = document.querySelector("select").selectedIndex;
navigator.clipboard.writeText(copyids[selectedIndex].name);
Upvotes: 0
Reputation: 15223
I made you a solution with the ability to select the desired data cell from the array. I've added a select
tag for you, listing the name of each cell.
And at the choice of a specific option
with you copy id in accordance with the specified name.
function copyToClipboard() {
var copyids = {
ids: [
{
name: "id1",
id: 192389021,
},
{
name: "id2",
id: 123879032,
},
{
name: "id3",
id: 149018292,
},
],
};
let selectIndex = document.querySelector("select").selectedIndex;
let storage = document.createElement("input");
storage.value = copyids.ids[selectIndex].id;
console.log(storage.value);
document.body.appendChild(storage);
storage.select();
document.execCommand("copy");
document.body.removeChild(storage);
}
<button onclick="copyToClipboard()">COPY</button>
<select>
<option value="id1">id1</option>
<option value="id2">id2</option>
<option value="id3">id3</option>
</select>
Upvotes: 0
Reputation: 190
Maybe this helps
function copyToClipboard() {
let temp = document.createElement('textarea');
temp.value = copyids.ids[0].id;
document.body.appendChild(temp);
temp.select();
document.execCommand('copy');
document.body.removeChild(temp);
}
Upvotes: 2
Reputation: 170
To copy, you will need to select before what you want to copy. Maybe you should put the data of the variable somewhere and copy it.
https://www.w3schools.com/howto/howto_js_copy_clipboard.asp
Upvotes: 0