11

I am unable to use the execCommand('copy'), trying to copy value which is selected in multi-select option. I am getting value in "temp" but the value which is getting in temp not copying or getting in clipboard.

{
        $propArr=array_unique($properties);
        echo "<div class='table-responsive'>";
            echo "<table class='bordered'>";
            foreach($propArr as $keyProp =>$val){
                echo "<tr>";
                    echo "<td>$val</td><td>";
                    echo "<select name='propval' id='propval' onclick='showpropval(this.value);' class='form-control' multiple>";
                    foreach($values as $k => $v){
                        if($val==$k){
                            foreach($v as $kv =>$fval){
                                echo "<option value='$fval'>$fval</option>";
                            }
                        }
                    }
                    echo "</select>";
                    echo"</td>";
                echo "</tr>";
            }
            echo "</table>";
        echo "</div>";
        }

<script>
        function showpropval(val)
        {
            var temp = val;
            temp.execCommand("copy");
            
        }
    </script>

8 Answers 8

14

I understand that your intention is the following: you want to copy the values of the selected options to the clipboard as soon as you select it.

When you use document.execCommand('copy'), you copy whatever is selected on the page (such as content in a paragraph or in an input field itself).

The catch is however that selecting options in <select> is not considered to be selected text. Worse yet, if you would like to trigger selecting text via javascript, there are some restrictions: you can only call .select() on an <input>or a <textarea> element.

Here is what I would do: copy the selected options to a separate (not visible) input-field, select it and copy the content from that.

Here is a fiddle that can serve as a demo: https://jsfiddle.net/Zomry/metcfvcq/13/

I wil break it down here:

First, add this element to the page. This is the input-field where we will copy the content from to the clipboard. Note that I have added tabindex -1 so you cannot reach it via tab key. I also included aria-hidden so screenreaders know it should ignore this.

<input class='copyfrom' tabindex='-1' aria-hidden='true'>

Then make the input field invisible by putting it off screen (did not work if I tried display: none; or other tricks)

<style>
    .copyfrom {
        position: absolute;
        left: -9999px;
    }
</style>

Then copy the value to the input field, select it and copy it.

var input = document.querySelector("input.copyfrom"); // select the input field

function showpropval(val) {
    var selectedValues = getSelectValues(this); // get selected values
    input.value = test.join(','); // join them in a comma separated list
    input.select(); // select offscreen inputs text
    document.execCommand("copy"); // copy it
    this.focus(); // focus back on original, so we don't see any glitches
} 

// credits to: https://stackoverflow.com/questions/5866169/how-to-get-all-selected-values-of-a-multiple-select-box
function getSelectValues(select) {
    var result = [];
    var options = select && select.options;
    var opt;

    for (var i=0, iLen=options.length; i<iLen; i++) {
        opt = options[i];

        if (opt.selected) {
          result.push(opt.value || opt.text);
        }
    }
  return result;
}
3
  • Its working fine, thanks a lot. got result as i expected.
    – Rajesh k
    Commented Jul 18, 2017 at 3:45
  • Might depend on the browser. I tested in the latest version of Chrome at that time. What browser are you trying?
    – Zomry
    Commented Feb 13, 2018 at 18:45
  • Thank you so much for saving our precious Time :)\ Commented Nov 27, 2019 at 12:27
12

In 2021, when compatibility with Internet Explorer is finally (almost) irrelevant, the simplest possible solution is:

function copyToClipboard(value) {
  navigator.clipboard.writeText(value)
}

2
  • This did the trick for me - incredibly helpful - thank you!
    – Ace
    Commented Aug 12, 2021 at 1:42
  • Still delivering value in 2024. document.execCommand("copy") was failing intermittently; this works every time.
    – Dave Land
    Commented Jul 4 at 1:50
5

Not directly related but seems like a good place to say this. When using the document.execCommand(), the element that is being used to supply the "text" must be visible on the page. So using display: none; will cause this to fail also trying to make the element height: 0; width: 0; also breaks this function. I got round this but positioning the element absolute and moving it far off the screen.

Hope this helps someone :-)

2

I had other case of "copy" command not working. ExecCommand returned true, but the value was not copied. In my case the problem was the function which executed the command (a Promise, to be exact). Maybe a small sample (using the function from Zomry's answer):

function copyToClipboardButtonHandler_Working() {
  //copy logic executed directly here works
  showpropval('this works');
}

function copyToClipboardButtonHandler_NotWorking() {
  //copy logic executed directly here works
  myService.doSomeLogicAndReturnPromiseWithAString().then(text =>
     showpropval(text) /*this does NOT work'*/
  );
}

If I interpret correctly, command has to be invoked in the same script execution iteration that was invoked by a human. Since Promise's callback is in other iteration, browser denies it (although it says it doesn't). I do not know if this is true, but the code works for me, which is fine ;)

2
  function CopyToClipboard(element) {
      var $temp = $("<input>");
      $("body").append($temp);
      $temp.val($(element).text()).select();
      document.execCommand("copy", false, $temp.val());
      $temp.remove();
  }
1

ok, my approach is a little bit easier:

  1. create an extra input with type 'text'
  2. on your function call copy the value of the selected option to the extra field
  3. give extra field position absolute and left -9999 so it exists in dom but not in the visible viewport!
  4. do the rest!

here's an example:

function copyUserName() {

    //just_for_copy is my invisible extra field
    document.getElementById('just_for_copy').value = document.getElementById('user_phone').value;

    var justForCopy = document.getElementById('just_for_copy');

    justForCopy.select();

    document.execCommand("copy");
}
0

Try this:

function showpropval(val) {
    var temp = val;
    document.execCommand("copy",false,val);
}
0
0

thanks to @Zomry I adapted your response to Typescript on Angular 9 and here is:

copyColor(colorCode: string) {
    // funcion que copia al clipboard
    const colorClicked = this.findColorObject(colorCode);
    const copyText = document.getElementById(`${colorClicked.id}`) as               HTMLInputElement;
    copyText.select();
    document.execCommand('copy');
  }
.input-color{
  /* visibility: hidden;
  height: 0px; */
  position: absolute;
  left: -9999px;
}
 <div *ngFor="let color of ColorList" class="col-4 p-0">
    <div (click)="copyColor(color.color)">
        <p>{{color.name}}</p>
        <input class="input-color" id="{{color.id}}" value="{{color.color}}" type="text" tabindex='-1' aria-hidden='true'/>
        <p>{{color.color}}</p>
      </div>
  </div>

I was trying to hidde the input but it doesn´t work until i found this solution in your CSS positioning. I hope someone find it usefull.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.