Search code examples
javascriptjqueryhtmlcopyenter

How do I make <div> into <textarea> copy to copy the line break too when hitting "enter keyboard button"?


How do I make when copying to to copy the line break too when i push enter keyboard button so that it is an exact copy? Right now it works, but it does not copy line break when pushing the enter keyboard button. And I want it to work as it does now without having it stripped.

NOTE because of former misunderstanding I clarify it: Please do not confuse "copying texatea into div" because that is not the same thing as "coping div into textarea", because the code working for "copying texatea into div" does not work the same as "coping div into textarea". I need to "coping div into textarea" and not the other way around.

I want: div into text

NOT: text into div

JavaScript:

function copyText() {
  $("#text").val($("#divtext").text())
}

html:

<textarea name="text" id="text" rows="14" cols="54" wrap="soft"></textarea>

Solution

  • It is hard to get line breaks from div if you use .text(), try using .html()

    Split <br> from div and join using \n for textarea

    $('#text').val($('#divtext').html().split('<br>').join('\n'))