Reputation: 3929
I have an address filled in <p>
tag. On click of edit button I turn that <p>
tag address into <textarea>
allowing user to edit it.
but whenever the user clicks on edit, the address text from <p>
tag is fetched in <textarea>
without line breaks.
HTML Markup:
<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 the problem, I have created a fiddle here demo
Upvotes: 5
Views: 5743
Reputation: 16804
To get line breaks use $(this).html()
instead of $(this).text()
.
To use the line breaks inside the textarea replace the <br>
with 

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, '
');
Updated JSFiddle
Upvotes: 6