Textarea line break jquery

I have a button “edit description”, when I click on it, the text disappears and appears

        if (id == 'commedit') jQuery(this).html('<textarea>'+jQuery(this).text()+'</textarea>');
        else if (id == 'commsave') {
            jQuery(this).text(jQuery(this).find('textarea').val());
        }

In MySql, I have this text - "tetee<br>afafaf<br>afafaf<br>afsafsasfasf"which displays line breaks, but when I click "edit" in the text area that appear with jQuery text appear without lines, and when I click "Save" they also appear in my description field in one long line without line breaks. So I need your help.

+5
source share
1 answer

<br>are html breaks. You want \nin the text box.

jQuery(this).html().replace(/<br>/gi,"\n")

When saving, you want to change it to breaks and use html () instead of text ();

var elem = jQuery(this);
if (id === 'commedit') {
    var text = jQuery(this).html().replace(/<br>/gi,"\n");
    elem.html('<textarea>'+ text +'</textarea>');
} else if (id === 'commsave') {
    var html = elem.find('textarea').val().replace(/\n/g,"<br>");
    elem.html(html);
}

JSFiddle example

+14
source

All Articles