Click to See Complete Forum and Search --> : auto add line breaks
Code One
03-25-2003, 10:38 PM
Anyone know how to auto add line breaks in textarea using javascript, or dhtml? If anyone has a script already that does this or can slap together one for me that would be great!!!!!
Thanks in advance
Code One
A line break in a textarea is \n
Code One
03-25-2003, 11:05 PM
say I have a textarea and I want to type some stuff in it, then save it as is without having to manaully type the br tag at the end of each line so that when the txt file is save the text would stay as is, instead of bunching up. Instead of going back and manually typing in the br tag I would have a script that would automatically add the line break for me. Do you know how to do that?
Thanks for the help!
Code One
edit: I think it has something to do with this line:
var theBR = document.createElement('BR');
Code One
03-25-2003, 11:12 PM
function addBRElementToEnd() {
var newElem = document.createElement("BR")
newElem.id = "newBR"
var newText = document.createTextNode("This is the next line.")
newElem.appendChild(newText)
document.body.appendChild(newElem)
}
I am totally guessing
Code One
Here is how I would do this:
<html>
<head>
<title>Line Breaks</title>
<script langugae="javascript" type="text/javascript">
function addbr(frm)
{
val = frm.mytext.value;
val = val.replace(/\n/g,"<br>");
document.getElementById("mydiv").innerHTML = val;
newval = document.getElementById("mydiv").innerHTML;
newval = newval.replace(/<br>/gi,"<br>\n");
document.mynewform.mynewtext.value = newval;
}
</script>
</head>
<body>
<form name="myform" onSubmit="addbr(this); return false;">
<textarea name="mytext" cols="50" rows="8"></textarea>
<br>
<input name="submit" type="submit" value="Submit">
</form>
Live Preview:
<div id="mydiv" style="width: 420px; height: 180px; border: 1px solid; overflow: auto;"></div>
<br>
Code Generated:
<form name="mynewform">
<textarea name="mynewtext" cols="50" rows="8"></textarea>
</form>
</body>
</html>
Code One
03-26-2003, 03:02 PM
thanks alot for the code!!!! I havent tried it yet but I bet it will do it.
Thanks alot!
Code One
Code One
03-26-2003, 04:31 PM
I checked out the code and its pretty rad. I was wondering though, is it possible to make all that happen in one textarea? or just two? That would be really nice. I already tried working it out myslef but I have to admit my Javascript skill are very limited. Thanks for all the help!
Code One
Mike Kane
07-19-2008, 05:27 PM
For those who might stumble on this thread in the future and not know much about JavaScript (like I did) there is a simple fix for this in PHP now
$string = nl2br($string);
One example is:
<?php
if(!isset($_POST['text'])) {
?>
<form name="myform" action="textarea_test.php" method="post">
<textarea name="text" width="50" height="10" /></textarea><br />
<input type="submit" name="Submit" Value="Submit" />
</form>
<?
} else {
$string = nl2br($_POST['text']);
echo $string;
};