0

I have a text displayed from database and I create a "Edit Text" button to edit it and save it. It works when the text from database is in one line but if I use an enter to text for going to the new line it doesn't work at all.

I remove the getting text from database part for easier testing that:

<?php
$rr="asdadsasd \n d"; 
?>
<form method="post" action="">
<input type="submit"  id="edp"value="EditPst">
<div class="post"id="pst"><?php echo nl2br($rr);?></div>
</form>
<script>
$(document).on("click", "#edp", function() { 
    $("#edp").replaceWith('');
    $("#pst").replaceWith('<textarea name="pps" class="post"id="pss"><?php echo nl2br($rr);?></textarea><input type="submit"  id="spp" value="save"name="svpst"><input type="submit"  id="canp" value="cansel">');
});
</script>

If you remove the \n part it works fine.

Twisty
  • 30,304
  • 2
  • 26
  • 45
  • 1
    Please clarify what you mean by *it doesn't work*. Do you see an error in Console? Since the content inside the element doesn't matter, it should work as expected. What were you expecting to have happen? – Twisty Jan 05 '20 at 22:11
  • if you just add a jquery.js file link and test it with "\n" in "$rr" variable and without it you find out the problem – 11111111111111111 Jan 05 '20 at 22:14
  • 1
    Does this answer your question? [How do I replace all line breaks in a string with
    tags?](https://stackoverflow.com/questions/784539/how-do-i-replace-all-line-breaks-in-a-string-with-br-tags)
    – Twisty Jan 05 '20 at 22:33
  • this creates another problem, when i change "\n" with
    when i click on edit text , in the edit text show the
    element
    – 11111111111111111 Jan 05 '20 at 22:43

1 Answers1

-2

I am unable to replicate the issue as you described it. PHP nl2br() just adds <br /> elements when it detects a New Line (\n) character.

nl2br — Inserts HTML line breaks before all newlines in a string

Returns string with <br /> or <br> inserted before all newlines (\r\n, \n\r, \n and \r).

Test with the following, excluding PHP that cannot be processed.

$(function() {
  $.fn.nl2br = function() {
    var re = RegExp("(?:\r\n|\r|\n)", 'g');
    var str = $(this).val();
    $(this).val(str.replace(re, "<br>"));
  }
  $("form").on("click", "#edp", function() {
    $("#edp").remove();
    var cnt = $("#pst").html();
    $("#pst").replaceWith('<textarea name="pps" class="post"id="pss"></textarea><input type="submit" id="spp" value="Save"name="svpst" /><input type="submit"  id="canp" value="Cancel" />');
    $("#pss").html(cnt);
  });
  $("form").submit(function(e) {
    e.preventDefault();
    $("#pss").nl2br();
    //return true;
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post" action="">
  <input type="submit" id="edp" value="EditPst">
  <div class="post" id="pst">asdadsasd <br /> d</div>
</form>
Community
  • 1
  • 1
Twisty
  • 30,304
  • 2
  • 26
  • 45