Nita Nita - 3 months ago 12
Javascript Question

Copy text button from the input

I have multiple records. Each record has an input with unique text prdefined and button to copy this text to clipboard. Everything works fine as long as i have only one record. In case of multiple records, only the first one seem to work. I will need help on make it work with many inputs and buttons, any advice? Another question is if is possible to hide an input (type='hidden'). I tried but it doesn't seem to work.

My HTML:

<input id='1' class="js-copytextarea" value='Sample Text to Copy 1 '>
<button class="js-textareacopybtn" data-id="1">COPY</button>
<br>
<input id='2' class="js-copytextarea" value='Sample Text to Copy 2 '>
<button class="js-textareacopybtn" data-id="2">COPY</button>


JavaScript:

var copyTextareaBtn = document.querySelector('.js-textareacopybtn');
copyTextareaBtn.addEventListener('click', function(event) {
var elem = $(this), selectedinput = elem.attr('data-id');
console.log(selectedinput);
var copyTextarea = document.querySelector('.js-copytextarea');
copyTextarea.select();

try {
var successful = document.execCommand('copy');
var msg = successful ? 'successful' : 'unsuccessful';
console.log('Copying text command was ' + msg);
} catch (err) {
console.log('Oops, unable to copy');
}
});


Link to jsFiddle:

https://jsfiddle.net/nitadesign/p58z0yrq/3/

Answer

As I see, you already attached the jQuery library to your code. So, you can use jQuery to make it easier.

$('.js-textareacopybtn').on('click', function(event) {
  var copyTextarea = $(this).data('id');
  $('#' + copyTextarea)[0].select();

  try {
    var successful = document.execCommand('copy');
    var msg = successful ? 'successful' : 'unsuccessful';
    console.log('Copying text command was ' + msg);
  } catch (err) {
    console.log('Oops, unable to copy');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input  id='1' class="js-copytextarea" value='Sample Text to Copy 1 '>
<button  class="js-textareacopybtn" data-id="1">COPY</button>
<br>    
<input  id='2' class="js-copytextarea" value='Sample Text to Copy 2 '>
<button class="js-textareacopybtn" data-id="2">COPY</button>

If you are going to copy from a hidden input, I recommend to use this: https://github.com/terinjokes/zClip