How to create a 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 code, and when I generate a random word, let's say "item1" shows how I can add a button under it so that when I click it I copy "item1"
I added some lines to your code, try it, it will work!
<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> You are looking for a script for:
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 must be a selectable element, that is, text input or text field: <input id="message">