tech @ Beacon Deacon

Keep the lines of a textarea

Jamie Johnson

June 18, 2018

Do you ever pass a textarea's value with a form only to have the first line the only thing that goes through (i.e., the textarea is truncated at first line)? Here's a way to resolve that with some simple JavaScript:

  1. Ensure you have id attributes on all your textareas in your form.
  2. Add this call onblur="textarealines(this.id);" to each textarea.
  3. Write this function in the head or top of the body of the page in question:
    <script>
    function textarealines(ta){
    	document.getElementById(ta).value=document.getElementById(ta).value.toString().replace(/\n\r?/g,' ');
    } 
    </script>
    

Test it out with the textarea below by typing and hitting enter to go to new lines and typing more (or go with what is already in there though you will have to at least click in the textarea if you do that), and then press the tab key or click out of it. Note, the textarea uses this HTML markup:

<textarea id="taexample" cols="60" rows="5" onblur="textarealines(this.id);"></textarea>

That's it!