Sudarshan Kalebere Sudarshan Kalebere - 5 months ago 10
Javascript Question

Line breaks are getting omitted when trying to edit

I have address filed in p tag, on click of edit button I turn that p tag address into textarea allowing user to edit it.
but whenever user clicks on edit the address text from p tag is fetched in textarea without line breaks.

Here is my code

<a href="" class="editShipAdd">Edit</a>
<a href="" class="saveShipAddBtn">Save</a>
<table class="table shipping-address-table">
<tbody>
<tr>
<td>
<div class="jumbotron custjumbo">
<p class="datainfo" id="shipping_address">123, Sample Street,<br> Sample Sample Road,<br> Bangalore, <br>Karnataka - 123xyz</p>
</div>
</td>
</tr>
</tbody>
</table>


JS code

$(".editShipAdd").on("click", function(e){
e.preventDefault();
var datasets = $('.shipping-address-table>tbody>tr td').find(".datainfo");
var savebtn = $('.saveShipAddBtn');
datasets.each(function(){
var theid = $(this).attr("id");
var newid = theid+"-form";
var currval = $(this).text().replace(/\r?\n/g, '<br />');

console.log(currval);

$(this).html('<textarea name="'+newid+'" id="'+newid+'" value="" class="form-control">'+currval+'</textarea>');
});

$(this).css("display", "none");
savebtn.css("display", "inline-block");
});

$(".saveShipAddBtn").on("click", function(e){
e.preventDefault();
var elink = $(this).prev(".editShipAdd");
var datasets = $('.shipping-address-table>tbody>tr td').find(".datainfo");
datasets.each(function(){
var newid = $(this).attr("id");
var einput = $("#"+newid+"-form");
var newval = einput.val().replace(/\r?\n/g, '<br />');
console.log(newval);
einput.remove();
$(this).html(newval);
});
$(this).css("display", "none");
elink.css("display", "inline-block");
});


To see exact problem, I have created fiddle here demo

Answer
  1. To get line breaks use $(this).html() instead of $(this).text().

  2. To use the line breaks inside the textarea replace the <br> with &#013;&#010; which is the ASCII equivalent.

This line:

var currval = $(this).text().replace(/\r?\n/g, '<br />');

Should be:

var currval = $(this).html().replace(/<br> ?/g, '&#013;&#010;');

Updated JSFiddle

Comments