简体   繁体   中英

New Line in textarea tag

I have a textarea tag in which I am inserting text with new lines. e:g like this :

abc
def
ghi

After Submitting the form,I am serializing all the form values including this textarea field.

the issues is that when I am trying to display this value (echo $textarea) ,it is giving the ouput without new lines. ie:

abc\r\ndef\r\nghi\r\n

Can anyone have any idea what is the issue here ??

here is my code.I am submiting my form with jquery

<script>
$(document).ready(function(){
var form = $('form');
var submit = $('#submit');
form.on('submit', function(e) {
e.preventDefault();  
$.ajax({
  url: 'comment.php',
  type: 'POST',
  cache: false,
   data: form.serialize(),     
  success: function(data){
    var item = $(data).hide().fadeIn(800);
    $('.section').prepend(item);  
  },
  error: function(e){
    alert(e);
  }
 });
 });
 });
</script>

here is the code through which I am trying to display the data

<div class="comment">
<div class="comment1">
<h3><?php echo $name ?> <span>said....</span></h3>
<p><?php echo nl2br($comment)?></p>
</div>
</div>

here's is how I am geting the $comment

<?php
if (isset( $_SERVER['HTTP_X_REQUESTED_WITH'] )):
include('./connection.php');
if (!empty($_POST['name']) AND !empty($_POST['textarea']) ) {
$name = mysql_real_escape_string($_POST['name']);
$comment = mysql_real_escape_string($_POST['textarea']); 
}
?>

use the echo nl2br($textarea) . It adds a br tag at every point that there is newline (newline to break)

It appears OP is showing the <textarea> content again without using a <textarea> again. Using nl2br() was in the right direction.

The solution is to change:

echo $comment;

into:

echo str_replace(array("\t","  "),array("&nbsp;&nbsp; &nbsp;","&nbsp;&nbsp;"),nl2br(htmlspecialchars($comment)));

edit

I see you are using mysql_real_escape_string(); when getting $comment . Remove mysql_real_escape_string() here, and put it only when you are going to use other mysql_* functions.

The mysql_real_escape_string() is messing up your new lines.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM