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

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of How to copy custom texts into clipboard when click on a button? without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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.

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.

We are here to answer your question about How to copy custom texts into clipboard when click on a button? - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji