Reputation: 735
I have a div contenteditable
in my web page.
When you type some text inside the div contenteditable
, the text is reproduced in a hidden textarea for the post treatment (form method="post" action="...").
For that, I retrieve the text from the div contenteditable
by using innerText
in Chrome, IE, and Safari, and textContent
in Firefox.
The problem is when I type newlines (by typing Enter key) inside the div contenteditable
, the newlines don't appear in the textarea, all the text in the textarea appear in one line.
Here the source code, very simple :
<style type="text/css">
.textarea{
overflow: hidden;
resize: none;
width: 100%;
white-space: pre-line;
border: solid #cccccc 1px ;
height: 34px;
}
</style>
<form style="width:500px;" method="post">
Div contenteditable :
<div class="textarea" contenteditable="true" onkeyup='copy_text_in_textarea(this);'></div>
<br>Textarea :
<textarea rows="2" class="textarea" id="textarea" name="textarea"></textarea>
</form>
<script type="text/javascript">
/*Function to reproduce div text in textarea :*/
function copy_text_in_textarea(this_contenteditable)
{
document.getElementById("textarea").value = this_contenteditable.textContent;
}
</script>
You can try it with firefox here : https://jsfiddle.net/Ls6j041g/
So how to preserve the newlines for the textarea ?
Thank you in advance, cordially.
Upvotes: 3
Views: 3459
Reputation: 1170
Just use .innerText instead.
function go() {
console.log(document.querySelector('#ok').innerText);
}
<span id="ok" contenteditable="true">Some Text<br/>with newlines
</span>
<button onclick="go()">click me</button>
Upvotes: 3
Reputation: 1
I use FF 42.0 on Windows 8. On FireFox, I use function html() instead of textContent (innerText does not work). In div contenteditable when we press enter it append "<br>" tag to div content. So I try to convert <br> tag to new line "\n" in javascript:
JS script:
jQuery.br2nl = function(varTest){
return varTest.replace(/<br>/g, "\n");
};
isFirefox = typeof InstallTrigger !== 'undefined';
if(isFirefox == true) {
message = $("#_chatText").html();
message = $.br2nl(message);
document.getElementById("_chatText").innerHTML = message;
message = document.getElementById("_chatText").textContent;
}
My HTML <div>
<div contentEditable="true" id="_chatText"></div>
Upvotes: 0