Reputation: 401
I have this simple code:
<div style="margin-left:10px;">
<p>
<a class="btn" href="#" onclick="myFunction()"><i class="icon-link"></i></a>
</p>
</div>
<div style="margin-left:10px;">
<div id="example-one" >
<p id="textEditor" contenteditable="true"></p>
</div>
</div>
<script type="text/javascript">
function myFunction()
{
// removes <div> from #textEdtor's content
$("#textEditor>div").replaceWith(function() { return $(this).contents(); });
var str=document.getElementById("textEditor").innerHTML;
var n=str.replace(/\n|\r/g, '<br>')
document.getElementById("textEditor").innerHTML=n;
alert(n);
}
</script>
The problem is that the var n=str.replace(/\n|\r/g, '<br>')
doesn't work when user press enter. Although it works very well if i use this .replace(/\[b\]/g,'<b>').replace(/\[\/b\]/g,'</b>')
It only adds a <br>
only if you press twice the enter.
Is there any way to fix this issue ?
Thank you.
Upvotes: 0
Views: 324
Reputation: 145428
The problem is in removing child <div>
elements. Replace your code with the one below, and everything should work fine:
function myFunction() {
$("#textEditor > div").before("<br />").contents().unwrap();
}
DEMO: http://jsfiddle.net/Hm7DY/
Upvotes: 1