Sudarshan Kalebere Sudarshan Kalebere - 1 year ago 66
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">
<div class="jumbotron custjumbo">
<p class="datainfo" id="shipping_address">123, Sample Street,<br> Sample Sample Road,<br> Bangalore, <br>Karnataka - 123xyz</p>

JS code

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


$(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){
var elink = $(this).prev(".editShipAdd");
var datasets = $('.shipping-address-table>tbody>tr td').find(".datainfo");
var newid = $(this).attr("id");
var einput = $("#"+newid+"-form");
var newval = einput.val().replace(/\r?\n/g, '<br />');
$(this).css("display", "none");
elink.css("display", "inline-block");

To see exact problem, I have created fiddle here demo

Answer Source
  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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download