Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create "copy to clipboard" button in html/javascript

<html>
<input type="button" id="btnSearch" value="Search" onclick="GetValue();" />
<p id="message" ></p>

<script>
function GetValue()
{
    var myarray= new Array("item1","item2","item3");
    var random = myarray[Math.floor(Math.random() * myarray.length)];
    //alert(random);
    document.getElementById("message").innerHTML=random;
}
</script>

</html>

this is the code and when i generate a random word lets say "item1" shows ,how can i add a button below it that when i click it copies the "item1"

like image 203
ammartjr Avatar asked Mar 26 '16 08:03

ammartjr


1 Answers

I've added some lines to your code ,try this it works !

<html>
<input type="button" id="btnSearch" value="Search" onclick="GetValue();" />
<p id="message" ></p><br>
<button onclick="copyToClipboard('message')">Copy</button>

<script>
function GetValue()
{
    var myarray= new Array("item1","item2","item3");
    var random = myarray[Math.floor(Math.random() * myarray.length)];
    //alert(random);
    document.getElementById("message").innerHTML=random;
}

function copyToClipboard(elementId) {


  var aux = document.createElement("input");
  aux.setAttribute("value", document.getElementById(elementId).innerHTML);
  document.body.appendChild(aux);
  aux.select();
  document.execCommand("copy");

  document.body.removeChild(aux);

}
</script>

</html>
like image 166
SeleM Avatar answered Oct 08 '22 16:10

SeleM