JQuery copy multiline list to clipboard

I spent some time figuring out which solution would copy the multi-line list to HTML, remove tags and indents from the onclick button without using Flash. In my research, I came across " jQuery by clicking the copy to clipboard button ", and I tested Alvaro Montoro's answer but the solution does not work in a multi-line list, but it works fine for the paragraph text. I do not intend to support the Clipbaord API because it shows very limited support in browsers. Studying further, I came across a “ HTML5 alternative to flash-based ZeroClipboard for safely copying data to the clipboard? ” And Thayne respond to the blog post links, but it will copy all the HTML. I figured out how to remove tags and indents:

HTML:

<button onclick="copyToClipboard('#therecipe')">Copy List</button> <div class="listing"> <ul id="someList"> <li>1 million</li> <li>Monday</li> <li>Something</li> <li>Foobar</li> <li>1tsp blah</li> </ul> </div> <textarea class="auto"></textarea> 

JQuery

 $('button').click(function(element) { var thelist = $('#someList').html(); thelist = thelist.replace(/\s+<li>/g, ''); thelist = thelist.replace(/<\/?li>/g, '\r'); $('.auto').val(thelist); }); 

How to copy a multi-line list item using jQuery, remove tags, remove padding and copy to clipboard without using Flash? Is there a plugin that supports all the latest browsers that I don't see?

+5
source share
1 answer

Note. This solution will work in IE10 +, Chrome 43+, Opera 29+ and Firefox 41+. Not for Safari!

You are most on the way, you just need select() <textarea> , and then use document.execCommand('copy') to load it to the clipboard.

 var copyTextarea = document.querySelector('.auto'); $('button').click(function(element) { var thelist = $('#someList').html(); thelist = thelist.replace(/\s+<li>/g, ''); thelist = thelist.replace(/<\/?li>/g, '\r'); $('.auto').val(thelist); copyTextarea.select(); document.execCommand('copy'); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button>Copy List</button> <div class="listing"> <ul id="someList"> <li>1 million</li> <li>Monday</li> <li>Something</li> <li>Foobar</li> <li>1tsp blah</li> </ul> </div> <textarea class="auto"></textarea> 

This requires <textarea> , but you can hide it with CSS. It will not be as simple as display:none , as this will disqualify him from being able to choose. You can install it from the screen or follow the detailed tip in This answer to make it invisible.

Additional spacing is due to indent your HTML, you can get rid of it by using String.prototype.trim() , but ideally I would instead build your list, passing DOM instead of using Regex.

+2
source

All Articles