Link to home
Start Free TrialLog in
Avatar of TheUndecider
TheUndeciderFlag for United States of America

asked on

Javascript to Insert a break line in TextArea boxes

Hello,

I'm working on a web page and I have these read only text areas where the user enters several options for the products they want.   When they enter these options I am able to create text boxes for each input, but when they go to the next page, all entered text becomes read only and it's displayed in one single textarea.  All fields are separated by a comma.

Is there a way that I can create a javascript code that looks for any textarea in the page, look for their content and enters a break <br> before a comma so the text looks easier to read?  These breaks are only for visual purposes, I don't want to edit the field values. I just want them to look better than one single line.

Here's 2 textareas where you can see what I'm talking about.  

<textarea readOnly class="cart" wrap="physical" name="0:freeopt" rows="4" cols="40" ID="Textarea1">Product,Widget,Type,Bucket,Color,Blue</textarea>

<textarea readOnly class="cart" wrap="physical" name="1:freeopt" rows="4" cols="40" ID="Textarea2">Product,Shell,Type,Wood,Color,Red</textarea>

I need them to look like this:

Product,
Widget,
Type,
Bucket,
Color,
Blue

Any ideas?

Thanks!
ASKER CERTIFIED SOLUTION
Avatar of leakim971
leakim971
Flag of Guadeloupe image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
>> Is there a way that I can create a javascript code that looks for any textarea in the page,

<html>
<head>
<script type="text/javascript">
function addLineBreaksInTextArea()
{
	var txtAreaObjs = document.getElementsByTagName("textarea");
	var regexComma = /[,]/g;
	for(var i=0;i<txtAreaObjs.length;i++){
		txtAreaObjs[i].value = (txtAreaObjs[i].value).replace(regexComma,",\r\n");
	}
}
window.onload=addLineBreaksInTextArea;
</script>
</head>
<body>
<textarea>hello,world</textarea>
<textarea>Welcome,to,EE</textarea>
<textarea>hi,there</textarea>
<textarea>greetings,buddy!</textarea>
</body>
</html>

Open in new window

SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
A break-tag (<br />) won't work inside a textarea.  In JavaScript you would print a break character, "\n".  This may vary depending on the language you're using.
<textarea rows="12" cols="50" id="myText"></textarea>
<script type="text/javascript">
document.getElementById('myText').innerHTML = "hello\nworld";
</script>

Open in new window

Avatar of TheUndecider

ASKER

Thanks!   It really worked!