Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery .val() function cleans up '\r\n' from textarea - why?

Tags:

jquery

I'm using $("#text").val() to get text from textarea field and send through ajax, but linebreaks (I mean \r\n in textarea) disappeares at all... Why could it be and how to prevent it?

Thanks!

like image 241
Vitalii Ponomar Avatar asked Dec 22 '11 09:12

Vitalii Ponomar


1 Answers

Taken from the documentation for val():

Note: At present, using .val() on textarea elements strips carriage return characters from the browser-reported value. When this value is sent to the server via XHR however, carriage returns are preserved (or added by browsers which do not include them in the raw value). A workaround for this issue can be achieved using a valHook as follows:

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

Adding the above snippet to your javascript will override the default behaviour of val() for textareas and will preserve whitespace.

See here for jsFiddle.

like image 101
Rich O'Kelly Avatar answered Nov 08 '22 12:11

Rich O'Kelly