Sumeet
Sumeet

Reputation: 1

Zeroclipboard multiple elements on same page in rails

I have 10 elements on one page in each do loop that should allow user to copy when someone clicks on button. I managed to add copy to clipboard functionality to rails using Zeroclipboard-rails gem. As I have multiple items on same page I have changed Id to Class.

 $(document).ready(function() {
    var clip = new ZeroClipboard($("#d_clip_button"))
  });

To this

    $(document).ready(function() {
    var clip = new ZeroClipboard($(".class_name"))
  });

But whenever I click on copy to clipboard button on any of 10 elements It selects the value of first item. How can I Fix This?

Here is the complete code. Thanks.

<script>
  $(document).ready(function() {
    var clip = new ZeroClipboard($(".my_clip_button"));


  $("#d-clip_button").on("click", function(){
    $("#fe_text").val("Copy me!");
  });
</script>

Upvotes: 0

Views: 248

Answers (1)

Peak Sornpaisarn
Peak Sornpaisarn

Reputation: 965

I have this problem before too. I use this code for copy to clipboard function

<script> 
  jQuery.fn.copyToClipBoard = function() { 
      var clip = new ZeroClipboard($(".copy_to_clipboard")); 
  } 
  $(function() { 
    $('.copy_to_clipboard').copyToClipBoard(); 
  }); 
 </script>

Just to play for fun! You can use this code as many time as you like in a loop like this:

  <% (1..10).each do |n| %>
   <button class="btn btn-success copy_to_clipboard" data-clipboard-text= <%= n %> > <p> Click ME </p> </button>
  <% end %>

I hope this code can help.

Upvotes: 0

Related Questions