All we need is an easy explanation of the problem, so here it is.
function myFunction() {
var copyText = document.getElementById("1");
var copyText = document.getElementById("2");
copyText.select();
navigator.clipboard.writeText(copyText.value);
alert("Copied the text: " + copyText.value);
}
<select id="1">
<option>Apple</option>
<option>Carrot</option>
</select>
<select id="2">
<option>Fruit</option>
<option>Vegetable</option>
</select>
<button onclick="myFunction()">Copy text</button>
When Apple and Fruit is selected in the drop down, and click Copy text button, my clipboard will have "Apple/Fruit"
I can’t figure it out. Please help.
How to solve :
I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.
Method 1
Let’s start with what’s wrong:
- you are reusing the same variable
copyText
for both elements, hens only the last element will be available in that variable. - as the error shows, element
select
(which is delcared intocopyText
variable) doesn’t have functionselect()
- you are trying copy to clipboard a value from a single element
So, to minimally fix your code you’ll need declare two different variables for your elements, and combine values from both into one:
function myFunction() {
var copyText1 = document.getElementById("1");
var copyText2 = document.getElementById("2");
var value = copyText1.value + "/" + copyText2.value;
navigator.clipboard.writeText(value);
alert("Copied the text: " + value);
}
<select id="1">
<option>Apple</option>
<option>Carrot</option>
</select>
<select id="2">
<option>Fruit</option>
<option>Vegetable</option>
</select>
<button onclick="myFunction()">Copy text</button>
Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0