Home > Net >  Button var to clipboard
Button var to clipboard

Time:05-15

In the funtion below there is this var link. By clicking on the button I want to copy the var to clipboard.

function displayUser(user) {
    
var text = `Account No.: ${user.userId} <br> Country: ${user.country} <br> 
 "<button onclick="copyToClipboard(link)"> Copy Link</button>"`;
var link = `${user.Url}`;

grid.innerHTML  = text;
}

function user(data) {
    data.result.roomList.forEach((user) => displayUser(user));
}

What I found here and tried is this funktion:

function copyToClipboard(link){
    var dummy = document.createElement("input");
    dummy.style.display = 'none';
    document.body.appendChild(dummy);
    dummy.setAttribute("id", "dummy_id");
    document.getElementById("dummy_id").value=link;
    dummy.select();
    document.execCommand("copy");
    document.body.removeChild(dummy);

By clicking on the button it says "link is not defined". Anyone know how to make this work?

Thanks in advance

CodePudding user response:

This section here should be:

function displayUser(user) {
    
    var link = user.Url;
    var text = `Account No.: ${user.userId} <br> Country: ${user.country} <br> 
    "<button onclick="copyToClipboard(${link})"> Copy Link</button>"`;

    grid.innerHTML  = text;
}

function user(data) {
    data.result.roomList.forEach((user) => displayUser(user));
}

The variable link was not accessible, because you defined it after, and also you did not enclose it correctly

CodePudding user response:

You could do it like this. This didn't make the copying to clipboard work, but that's how you can pass it to the function like you want it.

function displayUser(user) {
    
    var grid = document.getElementById("testgrid");
    console.log(grid);

    var link = `${user.Url}`;
    var text = `Account No.: ${user.userId} <br> Country: ${user.country} <br> 
     <button onclick="copyToClipboard('${link}')"> Copy Link</button>`;
    
    grid.innerHTML  = text;
}
    
function user(data) {
    data.result.roomList.forEach((user) => displayUser(user));
}

function copyToClipboard(link){
    console.log(link);
    var dummy = document.createElement("input");
    dummy.style.display = 'none';
    document.body.appendChild(dummy);
    dummy.setAttribute("id", "dummy_id");
    document.getElementById("dummy_id").value=link;
    dummy.select();
    document.execCommand("copy");
    document.body.removeChild(dummy);
}

displayUser({Url: "bla", country: "blabla"});
  • Related