Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Copy to clipboard works only once

Tags:

javascript

Tried to look everywhere, didn't find solution. I am using this JS:

function copy(containerid) {
    var range = document.createRange();
    document.getElementById(containerid).style.display = "block";
    range.selectNode(document.getElementById(containerid));
    window.getSelection().addRange(range);
    document.execCommand("Copy");
    document.getElementById(containerid).style.display = "none";
}

However using it in my View I can do it either only once or containeid keeps the same value. My View:

<input type="text" value="x1" id="x1" style="display:none"><input type="text" value="x2" id="x2" style="display:none">
<img src="~/images/new-post-16.png" onclick="copy('x1')"/> <img src="~/images/phone-30-16.png" onclick="copy('x2')" />

I tried to multiply the function and call it only for one element only, but it still copied only one instance, either x1 or after reload of page x2. Any ideas? Elements must be hidden.

like image 634
Marek Špeta Avatar asked Oct 20 '25 04:10

Marek Špeta


1 Answers

You're trying to add a selection to an already existing selection that is in a different control. That's not going to work. You're basically trying to have multi-cursor in two distinct text input.

If you clear your selection with window.getSelection().removeAllRanges(); just before your window.getSelection().addRange(range); it will work.

This is also why @Hari Das code works: selectAll replaces the selected range, it doesn't try to add it.

like image 100
ChatterOne Avatar answered Oct 23 '25 02:10

ChatterOne



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!