Add <br/> to line breaks in textarea

by Christopher McCulloh

HTML

<textarea id="guest-entry">
  this
  should
  break
</textarea>


<!-- Ignore the Test Button.. just for testing on jsfiddle -->
<button onclick="textareaReplaceLineBreaks('#guest-entry');">Test</button>

<div>
    <h3>Installation instructions</h3>
    <ul>
        <li>Make sure your <code>textarea</code> element has a unique ID attribute. In this demo we use <code>id="guest-entry"</code> for our textrea element</li>
        <li>Edit the HTML of your page and add the script in the Javascript pane on the left to your page inside a <code>&lt;script&gt;</code> tag.</li>
        <ul>
            <li>The best place to include the whole script is right after your <code>textarea</code> element.</li>
        </ul>
        <li>Then, find your BC "checkWholeForm" script-- it will have a unique it at the end of the function name In your checkWholeForm function you should notice a line that reads: <code>theForm.submit();</code> That is the command that actually submits your form so just before that command inside BC's checkWholeForm script, call your javascript function <code>textareaReplaceLineBreaks("#guest-entry");</code> and pass in the ID of your textarea element (in our case it's "guest-entry") </li>
        <li>That's it.  Now after the form passes validation and just before it's submitted it will update your textarea and replace all line breaks with <code><br/></code> tags.</li>
    </ul>
    </div>

CSS

textarea { width: 100% }

JavaScript

function textareaReplaceLineBreaks(textareaID) {
    (function($) {        
        if (!textareaID) var textareaID = "#guest-entry";
        var textarea = $(textareaID);
        
        textarea.val(
            $(textarea).val().replace(/(\r\n|\n)/g, "<br/>")
        );
        
    })(jQuery);        
}