1

I have to allow the user to enter carriage returns in text areas; something like:

Sentence 1
Sentence 2
...

I have to persist those carriage returns when loading and saving data. I use jQuery on the client side, and .NET on the server. Any suggestions on how to approach?

Thanks.

3 Answers 3

3

If by "persist" the line breaks (CRLF) you mean that you want to display it properly, as SO does, you need to remeber to replace the CRLF pair with <br/>CRLF.

Otherwise, all your text will appear sequentially.

5
  • 1
    that is what I want, but found that just replacing .replace(/\r/g, '\r<br>'); is not working consistently
    – krul
    Jun 24, 2009 at 3:02
  • If you're using RegEx I'd go with .replace(/\r\n/g, "\r").replace(/\r/g, "\n<br>") Jun 24, 2009 at 3:08
  • If youre using php, you can take the contents of the textarea and use nl2br() to convert new lines ("\n") to <br />
    – sqram
    Jun 24, 2009 at 3:09
  • 1
    Even simpler: .replace(/\r?\n/g, "<br>\n")
    – the.jxc
    Jun 24, 2009 at 3:17
  • Thanks, I forgot completely... it's the hour I think... and I guess decaf.. :-\ Jun 24, 2009 at 3:30
1

You don't need to do anything special. That's what <textarea>s do, and unless you make a specific effort to strip out the newlines on the server side you'll load the save them with a standard string no problem.

1
  • 1
    ...except in our old friend IE. I've got a similar issue where I'm returning a preformatted ASCII text file (with CRLFs) via a jquery AJAX call to populate a <textarea>. Works great in FF, Safari, Opera, Chrome, even Dolphin on my phone. But IE 7,8,9 ignore the CRLFs and I can one long illegible line.
    – SAL
    Jun 10, 2011 at 19:23
1

Use jQuery .val() hook:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.