Welcome Guest, Not a member yet? Register   Sign In
textarea not allowing linebreaks


Hilo guys,

This is quite strange but for my textarea when user type something, press enter key (newline) and submit, it does not display the "linebreak". To put it simply, my textarea does not seem to support line break.

I have a feeling because when the text are sent to database and retrieved, the linebreak (<br>) isn't saved at all. I also find it curious how forum textarea such as this one is able to maintain the linebreaks.

Here is my view:
//Create a textarea for Comments
     $commentForm = array('id' => 'commentForm');
     echo form_open('comment/addComment/', $commentForm);
     $comment = array(
        'name'        => 'comment',
        'rows'  => '4',
        'cols'        => '30',
        'id'   => 'commentbox',
        'onkeypress' => 'submitComment()',
     echo "<p>Your comment for this review:<br/>";
     echo form_textarea($comment);
     echo "</p>";

     echo "<p>";
     echo form_submit('submit', 'Post Comment');
     echo "</p>";
     echo form_hidden('reviewID', $row->reviewID);
     echo form_close();

Here is the Controller:
public function addComment()
  $comment = trim($this->input->post('comment'));
  $reviewID = $this->input->post('reviewID');
  if($comment != ''){
   //Get UserID from Session
   $userID = $this->members();  
   echo '<br/>Commenter = '.$userID;
   $this->comment_model->addComment($comment, $userID, $reviewID);
   echo 'Comment added!';
   echo 'You didnt comment anything :(';

Any idea on why the linebreak isn't saved?

HTML treats white space as the same, so whether you use 1, 2 or 30 spaces html would display it as just one space to the user.

Number of ways you can tackle this, set white space css property to pre
Wrap with <pre></pre> tag
Or insert the br tags when a user enters a new line

You'll need to use an WYSIWYG editor like TinyMCE. This will insert the necessary <br /> and <p> tags automatically. Just make sure you use the xss_clean function to sanitize the text.

Quote:You’ll need to use an WYSIWYG editor like TinyMCE.
No you don't. What a bloat just for a line break.

What you're looking for is the native php function nl2br($myTextAreaText). It stands for New Line 2 BReak, it basically replaces any line break with the html code <br/>

Use the above function when echo'ing out your data onto your view and you'll see line breaks where you expect them.
However, if you are "editing" your data inside a textarea don't use this function or you'll see html <br/> inside your textarea, which you don't want!

Theme © iAndrew 2016 - Forum software by © MyBB