0

I'm new to programming & I was building this to help me aid copy pasting common notes & content, which I have to do a lot at my work. Kindly check the program here https://jsbin.com/ruvodipomi/edit?html,js,output

<html>
<button onclick="copyToClipboard('#p1')">Hello</button><br>

   <p id="p1">Hello<br> World</p>

   <textarea cols="80" rows="25"></textarea>

</html>

<script>

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

</script>

So, if you click on the button 'Hello', it saves 'Hello World' in the clipboard. In this way I can make multiple buttons containing number of notes, which would make my work easier, instead of copying them from some document.

The problem is, I'm unable to break line in the elements For e.g. Instead of saving 'Hello World' in clipboard, I wish to save
'Hello
World'
However I'm unable to do so by using <br> <br /> <\n>
It is very important for the program to process breaks or at least accept them through tags.

I believe it has something to do with the Java function? But I'm not getting it.

Could you please have a look? Thanks so much^^

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
Nam-yi
  • 1
  • 1
  • Does this answer your question? [How to keep line breaks when using .text() method for jQuery?](https://stackoverflow.com/questions/22678446/how-to-keep-line-breaks-when-using-text-method-for-jquery) – Simon Dec 08 '19 at 09:22
  • Does this answer your question? [Copy to clipboard with break line](https://stackoverflow.com/questions/46041831/copy-to-clipboard-with-break-line) – Ritesh Khandekar Dec 08 '19 at 09:25
  • `$("")` will remove new lines so use `$(" – Ritesh Khandekar Dec 08 '19 at 09:27

1 Answers1

0

Get html() of p tag

Replace all <br> with \n

create textarea and copy:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button onclick="copyToClipboard('#p1')">Hello</button><br>

   <p id="p1">Hello<br> World</p>

   <textarea cols="80" rows="25"></textarea>


<script>

function copyToClipboard(element) {
  var $temp = $("<textarea>");
  $("body").append($temp);
  $temp.val($(element).html().toString().replace(/\<br\>/gi,"\n")).select();
  document.execCommand("copy");
  $temp.remove();
}

</script>
Ritesh Khandekar
  • 3,885
  • 3
  • 15
  • 30
  • That was amazing! I couldn't find this for weeks! Thank you so much. I'll definitely read more about this. – Nam-yi Dec 08 '19 at 10:02