How to copy data from a selection to the clipboard without plugins, etc.?

So the question is:

Is it possible to copy data from an element selectwithout additional plugins (jQuery is fine, but nothing else), for example:

stack overflow

The main problem here is:

var copyTextarea = document.querySelector('.js-copytextarea');
copyTextarea.select();

If we work with textarea- everything is in order, but for selectit it is not applicable. I cannot select data inside an element select.

Any ideas guys?

Use case: I want to set the function in onchangeevent for an element selectwith a list of values, copy these values ​​and paste into textareaor another element, it does not matter

+4
1

: textarea .

function copyToClipboard(text) {

  var textarea = $('<textarea />');
  textarea.val(text).css({
    width: '0px',
    height: '0px',
    border: 'none',
    visibility: 'none'
  }).appendTo('body');

  textarea.focus().select();

  try {
    if (document.execCommand('copy')) {
      textarea.remove();
      return true;
    }
  } catch (e) {
    console.log(e);
  }

  textarea.remove();
  return false;
}

$("select").on("change", function(){
   if(!copyToClipboard($(this).val()))
       console.log("Copy failed"); //Do something
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select>
<option>Select</option>
<option value="Copy me!">Copy me!</option>
</select>

document.execCommand('copy') .

+2

Source: https://habr.com/ru/post/1625847/


All Articles