8
<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"

ammartjr
  • 83
  • 1
  • 1
  • 4
  • 3
    Possible duplicate of [How do I copy to the clipboard in JavaScript?](http://stackoverflow.com/questions/400212/how-do-i-copy-to-the-clipboard-in-javascript) – Pedram Mar 26 '16 at 08:24
  • how do i add the code to the existing code that i have posted – ammartjr Mar 26 '16 at 08:26
  • i need a single button that when i click it automatically copies ,no need to re-type in a box again or anything – ammartjr Mar 26 '16 at 08:32
  • Possible duplicate of [Click button copy to clipboard using jQuery](https://stackoverflow.com/questions/22581345/click-button-copy-to-clipboard-using-jquery) – Devlopers Friend Jun 08 '17 at 06:40

2 Answers2

27

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>
SeleM
  • 9,310
  • 5
  • 32
  • 51
0

You're looking for the script to be:

function GetValue()
{
    var myarray = new Array("item1", "item2", "item3");
    var random = myarray[Math.floor(Math.random() * myarray.length)];
    var message = document.getElementById("message");
    message.value = random;
    message.select();
    document.execCommand('copy');
}

The message element needs to be a selectable element, i.e. a text input or textarea: <input id="message">

bschlueter
  • 3,817
  • 1
  • 30
  • 48