Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preserve line breaks and carriage return characters when using .val() in textarea - Jquery

Tags:

html

jquery

I have this html -:

<div id="myEditor" contenteditable="true"></div>
<textarea id="myArea"></textarea>

I have this jquery code -:

$("#myEditor").live("paste",function(){ 
var $this = $(this); 

setTimeout(function(){ $("#myArea").val($this.text()); },2);
                                     });

But when i use the above jquery code, all the line breaks and carriage returns are stripped off.

From Jquery documentation, I even tried using this , but in vain -:

$.valHooks.textarea = {
get: function( elem ) {
return elem.value.replace( /\r?\n/g, "\r\n" );
}                     };

But when I manually copy everything from div and paste it into textarea, line breaks are well preserved..
How do go about this issue. Thanks

like image 209
sanchitkhanna26 Avatar asked Jan 21 '26 22:01

sanchitkhanna26


1 Answers

Try this

$.valHooks.textarea = {
get: function( elem ) {
return elem.value.replace( /\r?\n/g, "<br />" );
}                     };
like image 176
draxxxeus Avatar answered Jan 24 '26 14:01

draxxxeus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!