Skip to content
Advertisement

How to copy custom texts into clipboard when click on a button?

I have an input, and would like to make have a copy link next to its label.

enter image description here

When I click copy I want to not only copy the input value, but I would like to prepend more texts.

http://www.test.com?code= + input value

How do I do that?

//copy text 
function getLink(id) {
    var copyText = document.getElementById(id);
    copyText.select();
    copyText.setSelectionRange(0, 99999); /* For mobile devices */
    document.execCommand("copy");
    alert("Copied the text: " + copyText.value);
}

With this code above, only copy the value.

Advertisement

Answer

You can edit the value in the current input element, and then restore it to the original value after copied the edited value. Something like this:

function getLink(e) {
  const copyPad = e.target.previousElementSibling,
    storedValue = copyPad.value,
    copyValue = 'http://www.test.com?code=' + storedValue;
  copyPad.value = copyValue;
  copyPad.select();
  copyPad.setSelectionRange(0, 99999); /* For mobile devices */
  document.execCommand("copy");
  console.log("Copied the text: " + copyPad.value);
  copyPad.value = storedValue;
}

const but = document.querySelector('#copyLink');
but.addEventListener('click', getLink);
<input><button id="copyLink">Copy</button>
<input> Paste here to check

A user can’t see changes to the input element, because the page is not rendered before all the JS has been executed.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement