Reputation: 51
How can I execute copy to clipboard with many inputs? I have this code
HTML CODE
<input type="text" value="Hello" id="myInput1">
<input type="text" value="World" id="myInput2">
<button onclick="myFunction()">Copy text</button>
SCRIPT CODE
<script>
function myFunction() {
var copyText1 = document.getElementById("myInput1");
var copyText2 = document.getElementById("myInput1");
copyText1.select();
copyText1.setSelectionRange(0, 99999)
document.execCommand("copy");
alert("Copied the text: " + copyText.value);
}
</script>
Upvotes: 4
Views: 1704
Reputation: 2412
You can add a third input field (or a textarea
if you also want to add a newline character) and simply hide it. And, just before executing the text select and copy commands, unhide the textarea and then again hide it.
function myFunction() {
var copyText1 = document.getElementById("myInput1");
var copyText2 = document.getElementById("myInput2");
var hiddenInput = document.getElementById("hiddenInput");
hiddenInput.value = "Description1: " + copyText1.value + "\nDescription2: " + copyText2.value;
hiddenInput.style.display = "";
hiddenInput.select();
hiddenInput.setSelectionRange(0, 99999);
document.execCommand("copy");
hiddenInput.style.display = "none";
alert("Copied the text:\n" + hiddenInput.value);
}
<input type="text" value="Hello" id="myInput1">
<input type="text" value="World" id="myInput2">
<textarea id="hiddenInput" style="display:none;"></textarea>
<button onclick="myFunction()">Copy text</button>
Upvotes: 1
Reputation: 22265
maybe this one ?
for more clipboard usage info => https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Interact_with_the_clipboard#Using_the_Clipboard_API
btCopy.onclick=_=>
{
// step 1: collect the input values (a method like so many others)
let inputs = {}
Array.from(new FormData(myForm),entry=>{inputs[ entry[0] ] = entry[1]})
let All_inputs = JSON.stringify(inputs)
// step 2 : write All_inputs into the clipboard
navigator.clipboard.writeText(All_inputs)
// as in your wishes...
alert('Copied the text: ' + All_inputs)
}
<form id="myForm">
<input type="text" name="Description1" value="Hello">
<input type="text" name="Description2" value="world">
</form>
<button id="btCopy">copy</button>
Upvotes: 0