Reputation: 413
I've got an if else statement. Switching between a text in <p>
tag and the same text in an editable <textarea>
The problem is that:
you press the edit button and script converts p tag to textarea. Text is converted fine with line breaks.
You press save. Text is converted correctly back into a p tag again.
You try to press edit again... but this time, the linebreaks are ignored!?
var curState = "Ret";
if (curState == "Gem"){
curState = "Ret";
var p = btn.closest("div").find("textarea");
var t = jQuery(this).closest("div").children("div").children('textarea').data();
var ta = jQuery("<p/>", {
"data": t
});
p.replaceWith(ta);
}else{
curState = "Gem";
var p = jQuery(this).closest("div").find("p");
var t = p.data()
var ta = jQuery("<textarea/>", {
"class": "editTextarea",
"data": t
});
p.replaceWith(ta);
}
Upvotes: 1
Views: 73
Reputation: 171700
One way is take the html from <p>
and insert it into another container then use replaceWith()
on the <br>
and pull that modified html out to use as value for the textarea
Simple working demo:
// create temporary element to insert the `<p>` html into
var $content = $('<div>').append($('p').html())
// replace <br> tags
$content.find('br').replaceWith('\n')
// set value using modified html
$('textarea').val( $content.html() )
p{border:2px solid #ccc; padding: 1em}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Line 1<br/><br><br/>Line 2
</p>
<textarea rows="10"></textarea>
Upvotes: 1
Reputation: 4481
You have to retrieve the content of p
element with html()
instead of data()
.
Once you have the content, replace <br>
by \n
:
var t = p.html()
var ta = jQuery("<textarea/>", {
"class": "editTextarea"
});
ta.val(t.replace('<br>', '\n');
Upvotes: 0