The HTML code below is a loop result. All I want is to copy the input value by clicking the button, but I can’t make it work.
function myFunction() {
// Get the text field
var copyText = document.getElementById("myInput");
// Select the text field
copyText.select();
copyText.setSelectionRange(0, 99999); // For mobile devices
// Copy the text inside the text field
navigator.clipboard.writeText(copyText.value);
// Alert the copied text
alert("Copied the text: " + copyText.value);
}
<input type="text" value="Hello World" id="myInput">
<button onclick="myFunction()">Copy text</button>
<input type="text" value="Hello World fdasfds" id="myInput">
<button onclick="myFunction()">Copy text</button>
<input type="text" value="Hello World fdasfd fsdafds" id="myInput">
<button onclick="myFunction()">Copy text</button>
If there is only one entry, it works perfectly.
function myFunction() {
// Get the text field
var copyText = document.getElementById("myInput");
// Select the text field
copyText.select();
copyText.setSelectionRange(0, 99999); // For mobile devices
// Copy the text inside the text field
navigator.clipboard.writeText(copyText.value);
// Alert the copied text
alert("Copied the text: " + copyText.value);
}
<input type="text" value="Hello World fdasfd fsdafds" id="myInput">
<button onclick="myFunction()">Copy text</button>
>Solution :
The identifier is called an identifier because it identifies one element. If you use it for three elements, only the first ID will take effect, and the browser will ignore the others.
For three input fields, use three different IDs.
Example
function myFunction(id) {
// Get the text field
var copyText = document.getElementById(id);
// Select the text field
copyText.select();
copyText.setSelectionRange(0, 99999); // For mobile devices
// Copy the text inside the text field
navigator.clipboard.writeText(copyText.value);
// Alert the copied text
alert("Copied the text: " + copyText.value);
}
<input type="text" value="Hello World 1st input" id="myInput-1">
<button onclick="myFunction('myInput-1')">Copy text</button>
<input type="text" value="Hello World 2nd input" id="myInput-2">
<button onclick="myFunction('myInput-2')">Copy text</button>
<input type="text" value="Hello World 3rd input" id="myInput-3">
<button onclick="myFunction('myInput-3')">Copy text</button>
More information
idattribute – MDN Docs- Why are duplicate ID values not allowed in HTML? – StackOverflow Answer